@mastra/factory 0.29.0-alpha.7 → 0.29.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +50 -20
  2. package/dist/boards/board-events.d.ts +23 -0
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +37 -3
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts +6 -4
  7. package/dist/boards/board-writes.d.ts.map +1 -1
  8. package/dist/boards/board-writes.js +9 -6
  9. package/dist/boards/board-writes.js.map +1 -1
  10. package/dist/boards/intake-routing.d.ts +30 -16
  11. package/dist/boards/intake-routing.d.ts.map +1 -1
  12. package/dist/boards/intake-routing.js +41 -28
  13. package/dist/boards/intake-routing.js.map +1 -1
  14. package/dist/boards/project-boards.d.ts +15 -0
  15. package/dist/boards/project-boards.d.ts.map +1 -1
  16. package/dist/boards/project-boards.js +43 -7
  17. package/dist/boards/project-boards.js.map +1 -1
  18. package/dist/factory.d.ts +4 -14
  19. package/dist/factory.d.ts.map +1 -1
  20. package/dist/factory.js +22 -15
  21. package/dist/factory.js.map +1 -1
  22. package/dist/integrations/github/integration.d.ts.map +1 -1
  23. package/dist/integrations/github/integration.js +101 -0
  24. package/dist/integrations/github/integration.js.map +1 -1
  25. package/dist/integrations/github/rules.d.ts.map +1 -1
  26. package/dist/integrations/github/rules.js +7 -3
  27. package/dist/integrations/github/rules.js.map +1 -1
  28. package/dist/integrations/github/sandbox.d.ts +7 -1
  29. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  30. package/dist/integrations/github/sandbox.js +15 -1
  31. package/dist/integrations/github/sandbox.js.map +1 -1
  32. package/dist/integrations/github/session-subscriptions.js +1 -1
  33. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  34. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  35. package/dist/integrations/gitlab/rules.js +2 -1
  36. package/dist/integrations/gitlab/rules.js.map +1 -1
  37. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  38. package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
  39. package/dist/integrations/slack/channel-reply-processor.d.ts +1 -0
  40. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  41. package/dist/integrations/slack/channel-reply-processor.js +4 -1
  42. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  43. package/dist/integrations/slack/run-error-card.js +6 -1
  44. package/dist/integrations/slack/run-error-card.js.map +1 -1
  45. package/dist/links.d.ts +4 -2
  46. package/dist/links.d.ts.map +1 -1
  47. package/dist/links.js +5 -3
  48. package/dist/links.js.map +1 -1
  49. package/dist/routes/boards.d.ts +1 -1
  50. package/dist/routes/boards.d.ts.map +1 -1
  51. package/dist/routes/boards.js.map +1 -1
  52. package/dist/routes/contracts.d.ts +32 -5
  53. package/dist/routes/contracts.d.ts.map +1 -1
  54. package/dist/routes/contracts.js +36 -9
  55. package/dist/routes/contracts.js.map +1 -1
  56. package/dist/routes/intake-check.d.ts.map +1 -1
  57. package/dist/routes/intake-check.js +3 -1
  58. package/dist/routes/intake-check.js.map +1 -1
  59. package/dist/routes/intake-routes.d.ts +0 -3
  60. package/dist/routes/intake-routes.d.ts.map +1 -1
  61. package/dist/routes/intake-routes.js +1 -1
  62. package/dist/routes/intake-routes.js.map +1 -1
  63. package/dist/routes/skills.d.ts +1 -1
  64. package/dist/routes/skills.d.ts.map +1 -1
  65. package/dist/routes/skills.js +92 -28
  66. package/dist/routes/skills.js.map +1 -1
  67. package/dist/routes/surface.d.ts +0 -3
  68. package/dist/routes/surface.d.ts.map +1 -1
  69. package/dist/routes/surface.js +0 -1
  70. package/dist/routes/surface.js.map +1 -1
  71. package/dist/rules/dispatch-errors.d.ts +6 -0
  72. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  73. package/dist/rules/dispatch-errors.js +10 -1
  74. package/dist/rules/dispatch-errors.js.map +1 -1
  75. package/dist/rules/dispatcher.d.ts.map +1 -1
  76. package/dist/rules/dispatcher.js +74 -32
  77. package/dist/rules/dispatcher.js.map +1 -1
  78. package/dist/rules/event-rules.d.ts +3 -2
  79. package/dist/rules/event-rules.d.ts.map +1 -1
  80. package/dist/rules/event-rules.js +5 -3
  81. package/dist/rules/event-rules.js.map +1 -1
  82. package/dist/rules/public-failure-reason.d.ts +11 -0
  83. package/dist/rules/public-failure-reason.d.ts.map +1 -0
  84. package/dist/rules/public-failure-reason.js +136 -0
  85. package/dist/rules/public-failure-reason.js.map +1 -0
  86. package/dist/rules/transition-service.d.ts +13 -0
  87. package/dist/rules/transition-service.d.ts.map +1 -1
  88. package/dist/rules/transition-service.js +5 -1
  89. package/dist/rules/transition-service.js.map +1 -1
  90. package/dist/rules/types.d.ts +12 -0
  91. package/dist/rules/types.d.ts.map +1 -1
  92. package/dist/rules/types.js.map +1 -1
  93. package/dist/rules/validation.d.ts.map +1 -1
  94. package/dist/rules/validation.js +11 -2
  95. package/dist/rules/validation.js.map +1 -1
  96. package/dist/run-error.d.ts +1 -1
  97. package/dist/run-error.d.ts.map +1 -1
  98. package/dist/run-error.js +21 -12
  99. package/dist/run-error.js.map +1 -1
  100. package/dist/session/environment-state-processor.d.ts.map +1 -1
  101. package/dist/session/environment-state-processor.js +6 -2
  102. package/dist/session/environment-state-processor.js.map +1 -1
  103. package/dist/session/source-control-tools.d.ts.map +1 -1
  104. package/dist/session/source-control-tools.js +5 -3
  105. package/dist/session/source-control-tools.js.map +1 -1
  106. package/dist/skills/app-skills.d.ts +3 -2
  107. package/dist/skills/app-skills.d.ts.map +1 -1
  108. package/dist/skills/app-skills.js +5 -3
  109. package/dist/skills/app-skills.js.map +1 -1
  110. package/dist/skills/catalog.d.ts +23 -4
  111. package/dist/skills/catalog.d.ts.map +1 -1
  112. package/dist/skills/catalog.js +61 -28
  113. package/dist/skills/catalog.js.map +1 -1
  114. package/dist/storage/domains/audit/actions.d.ts +1 -1
  115. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  116. package/dist/storage/domains/audit/actions.js +6 -1
  117. package/dist/storage/domains/audit/actions.js.map +1 -1
  118. package/dist/storage/domains/boards/base.d.ts +12 -0
  119. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  120. package/dist/storage/domains/boards/base.js +3 -0
  121. package/dist/storage/domains/boards/base.js.map +1 -1
  122. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  123. package/dist/storage/domains/boards/schemas.js +4 -0
  124. package/dist/storage/domains/boards/schemas.js.map +1 -1
  125. package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
  126. package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
  127. package/dist/storage/domains/skill-overrides/base.js +54 -1
  128. package/dist/storage/domains/skill-overrides/base.js.map +1 -1
  129. package/dist/storage/domains/work-items/base.d.ts +2 -0
  130. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  131. package/dist/storage/domains/work-items/base.js +13 -5
  132. package/dist/storage/domains/work-items/base.js.map +1 -1
  133. package/dist/tools/audit-events-tool.d.ts +1 -1
  134. package/dist/tools/read-tools.d.ts.map +1 -1
  135. package/dist/tools/read-tools.js +0 -1
  136. package/dist/tools/read-tools.js.map +1 -1
  137. package/dist/tools/work-item-tools.d.ts.map +1 -1
  138. package/dist/tools/work-item-tools.js +0 -3
  139. package/dist/tools/work-item-tools.js.map +1 -1
  140. package/dist/work-items/create-work-item.d.ts.map +1 -1
  141. package/dist/work-items/create-work-item.js +2 -1
  142. package/dist/work-items/create-work-item.js.map +1 -1
  143. package/dist/workspace.d.ts +5 -1
  144. package/dist/workspace.d.ts.map +1 -1
  145. package/dist/workspace.js +69 -9
  146. package/dist/workspace.js.map +1 -1
  147. package/package.json +7 -7
package/README.md CHANGED
@@ -772,6 +772,7 @@ A phase's `runner.skill` runs a skill when a card enters the phase. Use a built-
772
772
  1. **Code skills** — passed to `new MastraFactory({ skills })`, created with `createSkill()` from `@mastra/core/skills`.
773
773
  2. **Folder skills** — `src/mastra/factory-skills/<name>/SKILL.md` in your app. `mastra build` copies the folder into the build output. The older `src/mastra/public/factory-skills` still works; when both exist, `src/mastra/factory-skills` wins. Factory also looks in `public/factory-skills`, `factory-skills` and `output/factory-skills` under the working directory, and uses the first that exists. Supporting files, such as `references/`, can sit next to `SKILL.md`.
774
774
  3. **Built-in skills** shipped with `@mastra/factory`.
775
+ 4. **Factory skills** — skills an organization admin created for one Factory in Settings › Skills (see [Create skills for one Factory](#create-skills-for-one-factory)). They only fill names the first three don't use.
775
776
 
776
777
  A skill with the same name as a built-in skill replaces it, for the built-in boards too. A code skill replaces the whole folder skill of the same name, including its supporting files. Repository skills in a project's own repository never replace these.
777
778
 
@@ -834,6 +835,20 @@ An edited skill shows an **Edited** badge. When the original changes after the e
834
835
 
835
836
  Saves and reverts are recorded in the audit log as `factory.skill.updated` and `factory.skill.reverted`. The API is `PUT` and `DELETE` on `/web/factory/projects/:id/skills/:name`, and `GET /web/factory/skills?projectId=<id>` lists a Factory's skills with its edits.
836
837
 
838
+ ### Create skills for one Factory
839
+
840
+ Organization admins can also add a skill to one Factory without changing the app. Open Settings › Skills, choose **New skill**, enter a name, a description and instructions, and choose **Create**. The name uses 1–64 lowercase letters, digits and single hyphens, such as `release-notes`, and can't be one an app or built-in skill already uses; edit that skill instead.
841
+
842
+ A created skill belongs to that Factory only and shows a **Custom** badge. Its sessions can load it from their next start, like any other skill, and a phase of its boards can run it as `runner.skill`. `factory.upsertBoard()` accepts a board that runs a created skill only when `projects` lists the projects, and each of them must have created it; a board for `'all'` projects may only run the app's skills. Choose **Edit** to change it, and **Delete** to remove it; a phase that runs a deleted skill shows it as missing, and cards entering that phase fail to start until you pick another skill. A repository skill with the same name is hidden in that Factory's sessions, as it is for app skills.
843
+
844
+ If your app later ships a skill under the same name, the app's skill takes over the name and the Factory's text becomes an edit of it: it keeps applying, the editor notes that the original changed, and **Revert to original** switches to the app's skill.
845
+
846
+ Creating and deleting are recorded in the audit log as `factory.skill.created` and `factory.skill.deleted`; changes to a created skill as `factory.skill.updated`. The API is `POST /web/factory/projects/:id/skills` with `{ "name", "content" }`, where `content` is the full `SKILL.md` whose frontmatter `name` matches; `PUT` and `DELETE` on `/web/factory/projects/:id/skills/:name` update and delete it. `GET /web/factory/skills?projectId=<id>` lists created skills with `origin: "project"`. From the CLI:
847
+
848
+ ```bash
849
+ mastra api factory skill create <project-id> '{"name":"release-notes","content":"---\nname: release-notes\ndescription: Write release notes for a merged change\n---\n\n# Release notes\n"}'
850
+ ```
851
+
837
852
  ### Execute a custom board
838
853
 
839
854
  Custom boards can create linked items, start working roles, transition through bound tools, and react to completed tool results. Board and phase identifiers contain 1–128 letters, digits, underscores, or hyphens and start with a letter or digit. Identifiers are case-sensitive and cannot contain surrounding whitespace.
@@ -1003,7 +1018,7 @@ The default routes are stored routes like any other: list them, edit them, disab
1003
1018
  | `enabled` | Defaults to `true`. Disabled routes are skipped. |
1004
1019
  | `on` | The board events the route handles: `work_item.created` (the default: new issues and pull requests), `work_item.opened`, `work_item.reopened`, `work_item.updated`, `work_item.closed`, `pull_request.opened`, `pull_request.reopened`, `pull_request.updated`, `pull_request.synchronized`, `pull_request.review_requested`, `pull_request.merged` and `pull_request.closed`. Each at most once. `work_item.commented` and `work_item.edited` are activity, which never moves a card, so a route can't name them. |
1005
1020
  | `when` | A rule over the card's facts (the same format as `autoStartWhen`). `null`, the default, matches every card. Every route can test `item.hasPullRequest` (an issue with an open pull request attached) and `item.hasIssue` (a pull request that closes or links an issue). A route that handles more than arrivals (`work_item.opened`, `work_item.created`) can also test `event.type`, `event.reason` and `card.phase` (the phase the card is in); a route on `work_item.updated` or `pull_request.updated` can test `event.labels.added`, `event.labels.removed`, `event.assignees.added` and `event.assignees.removed`. `item.key`, `item.title`, `item.state`, `source.integration`, `item.pullRequest`, `closedIssue.phase` and `closedIssue.hasPullRequest` are legacy filters: stored routes using them keep evaluating, but the editor no longer offers them. |
1006
- | `target` | Required. `{ boardKey, phaseKey?, moveToBoardKey? }` sets where matching cards land; without `phaseKey` they land in the board's first phase. The board must be installed in the project (code or stored). For a route that files new cards (`work_item.opened`, `pull_request.opened` or `work_item.created`), the phase can't be terminal and must be reachable from the board's first phase; a route that only moves existing cards can target any phase, terminal ones included. `moveToBoardKey` lets a route on `boardKey` that names none of those events send them to `phaseKey` on another installed board (see [Status events](#status-events-move-existing-cards)). `joinClosedIssue: true` is retired: a new route can't set it (`422 join_retired`), and a stored one can only be switched off. |
1021
+ | `target` | Required. `{ boardKey, phaseKey?, moveToBoardKey? }` sets where matching cards land; without `phaseKey` they land in the board's first phase. The board must be installed in the project (code or stored). For a route that files new cards (`work_item.opened`, `pull_request.opened` or `work_item.created`), the phase can't be terminal; any other phase of the board works, even one the first phase can't move to. A route that only moves existing cards can target any phase, terminal ones included. `moveToBoardKey` lets a route on `boardKey` that names none of those events send them to `phaseKey` on another installed board (see [Status events](#status-events-move-existing-cards)). `joinClosedIssue: true` is retired: a new route can't set it (`422 join_retired`), and a stored one can only be switched off. |
1007
1022
 
1008
1023
  Routes are evaluated in `position` order (0 first). Rules can test the [card facts](#phase-runners-automatic-starts-and-exit-tools) phase rules test, `source.repository` and `item.labels` among them. For pull requests, routes can also test `pullRequest.closesIssue` (`true` when the body closes an issue that has a usable card), `closedIssue.phase` and `closedIssue.hasPullRequest` (that card's phase and whether it already carries a pull request). These three are route-only: phase rules can't use them. On the `pull_request.opened` a linked pull request sends its card, `closedIssue.*` describe the card as it was before the pull request linked. A card already in its review phase doesn't start a second review when another pull request links: the review in progress keeps its pull request. That's why the default rule requires `closedIssue.hasPullRequest` to be `false`. `item.trusted` is `true` when the card carries an `authorTrusted: true` or `factoryAuthored: true` stamp. GitHub and GitLab stamp `authorTrusted` from the author's repository permission, and a stamp that is missing counts as untrusted.
1009
1024
 
@@ -1021,20 +1036,35 @@ A pull request routed to a board with a [pull request loop](#the-pull-request-lo
1021
1036
 
1022
1037
  Each board owns its intake rules: a rule places cards on its own board only, and each board has at most 100. A project also keeps an **intake order**, separate from the sidebar order: the order its boards are asked to take a new item. Under the intake order evaluator, intake asks each board in that order, and inside a board its rules top to bottom; the first enabled rule that matches and whose phase can take the card decides. Nothing names a board to fall back to. An item no board takes is **Not routed**: no card is filed, and the item is kept with the reason so an admin can fix a rule and route it again. A card created without a board that no board takes is refused with `intake_board_required` (422), so the person picks the board; `factory_create_work_item` takes that board as `board`. While the intake rules can't be read (stored boards unavailable), arrivals wait and retry, and a card created without a board is refused the same way.
1023
1038
 
1024
- Each project has its own evaluator. A project created since this release is stamped with `intake-order` as it is created, in the same write. A project from before it has no setting and keeps `route-list`, the evaluator described above (one list across all boards, then the default board's first phase), until an admin switches it with `PUT .../intake-order` and `{ "evaluator": "intake-order" }` (audited as `factory.intake_order.evaluator_updated`). `MastraFactory({ intake: { evaluator } })` or `FACTORY_INTAKE_EVALUATOR` (`intake-order` or `route-list`) forces one evaluator on every project, whatever its setting; the option wins over the variable. Set the same on every replica. A project uses `route-list` only when its setting was read and is empty: while the setting can't be read (stored boards unavailable), its arrivals wait and retry, a card created without a board is refused with `intake_board_required`, and Route again is refused, unless `route-list` is forced. During a rolling deploy, a replica still on an older release ignores the setting and decides every project by `route-list`, so a new project's items can be routed by the route list until every replica runs this release; a project created on such a replica gets no setting and stays on `route-list` until switched.
1039
+ New projects use the intake order. Every project created since this release is stamped with `intake-order` as it is created, and nothing needs to be set.
1040
+
1041
+ A project from before it has no setting and keeps `route-list`, the older evaluator: one list across all boards, then the default board's first phase. `route-list` exists only so those projects keep routing as they did until someone switches them. A project uses it only when its setting was read and is empty: while the setting can't be read (stored boards unavailable), its arrivals wait and retry, a card created without a board is refused with `intake_board_required`, and Route again is refused.
1042
+
1043
+ ##### Switching an existing project to the intake order
1044
+
1045
+ 1. Check what the project would do. `GET .../intake-order` returns the evaluator in use, its `evaluatorSource` (`legacy` for a project with no setting), and a comparison of both evaluators over the newest 200 items: `differing` counts items that would land on another board, `notRouted` those no board would take. Fix the rules until `notRouted` is what you expect; an item no board takes is Not routed, not filed on a default board.
1046
+ 2. Switch it. An admin sends `PUT .../intake-order` with `{ "evaluator": "intake-order" }`, audited as `factory.intake_order.evaluator_updated` with the evaluator before and after. With the CLI:
1047
+
1048
+ ```sh
1049
+ mastra api factory intake-order set <project-id> '{"evaluator":"intake-order"}'
1050
+ ```
1051
+
1052
+ Sending `{ "evaluator": "route-list" }` switches it back.
1053
+
1054
+ `FACTORY_INTAKE_EVALUATOR` forces one evaluator on every project, whatever its setting. It is meant for legacy deployments: set it to `route-list` to keep every project on the route list, or to `intake-order` to move every legacy project at once without switching them one by one. Set the same value on every replica. During a rolling deploy, a replica still on an older release decides every project by `route-list`, and a project created on such a replica gets no setting and stays on `route-list` until switched.
1025
1055
 
1026
1056
  Until an admin sets it, a project's intake order is derived from the route list: boards by the position of their first enabled rule that places new cards, then boards with no such rule, in sidebar order. A project whose rules for each board sit together routes exactly as before. A project whose rules interleave boards can route differently. While the order is derived, every rule write (create, edit, delete, reorder, or deleting a board with rules) derives it again. Setting the order with `PUT .../intake-order` fixes it: rule writes no longer change it. A board created later goes into the order just above the first board whose rules end in an enabled rule with no condition (a catch-all), or last when no board has one. Deleting a board deletes its rules, each with a `factory.intake_route.deleted` audit entry carrying `cause: "board_deleted"`, and drops it from the order.
1027
1057
 
1028
- | Request | What it does |
1029
- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1030
- | `GET /web/factory/projects/:id/intake-routes?boardKey=…` | One board's rules, in their order. |
1031
- | `POST /web/factory/projects/:id/intake-routes/reorder` | With `boardKey`, `ids` names every rule of that board; they swap among the places that board's rules hold, and other boards' rules stay put. Admin only. |
1032
- | `PATCH /web/factory/projects/:id/intake-routes/:routeId` | Under the intake order evaluator, a `target.boardKey` other than the rule's own board is refused with `intake_route_board_fixed` (422). |
1033
- | `GET /web/factory/projects/:id/intake-order` | The boards in intake order, whether the order is `derived` or `explicit`, the evaluator in use with `evaluatorSource` (`option`, `env`, `project`, or `legacy` for a project with no setting) and the project's own `projectEvaluator`, and a comparison of both evaluators over the project's newest 200 items against that order (`compared`, `differing`, `notRouted`), worked out on every read. |
1034
- | `PUT /web/factory/projects/:id/intake-order` | `{ boardKeys }`, every board once, refused with `intake_order_set_mismatch` (409) otherwise. Admin only; audited as `factory.intake_order.updated`. |
1035
- | `GET /web/factory/projects/:id/intake/not-routed` | Items no board took and nobody has filed since, oldest first, with the reason. Paged: `limit` (default 50, at most 100) and `cursor`, the `nextCursor` of the page before (null on the last). |
1036
- | `POST /web/factory/projects/:id/intake/not-routed/:decisionId/route-again` | Runs intake for the item again, by intake order whichever evaluator the replica runs. Refused with `intake_not_routed` (422) while no board's rules take it; otherwise 202, and the dispatcher files it where the rules say. Admin only; audited as `factory.intake.routed_again`. |
1037
- | `GET /web/factory/projects/:id/intake/skipped` | Each card-move rule that matched but was skipped because its target couldn't take the card, in the last 30 days: `routeId`, `count`, and the newest skip as `latest`. |
1058
+ | Request | What it does |
1059
+ | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1060
+ | `GET /web/factory/projects/:id/intake-routes?boardKey=…` | One board's rules, in their order. |
1061
+ | `POST /web/factory/projects/:id/intake-routes/reorder` | With `boardKey`, `ids` names every rule of that board; they swap among the places that board's rules hold, and other boards' rules stay put. Admin only. |
1062
+ | `PATCH /web/factory/projects/:id/intake-routes/:routeId` | Under the intake order evaluator, a `target.boardKey` other than the rule's own board is refused with `intake_route_board_fixed` (422). |
1063
+ | `GET /web/factory/projects/:id/intake-order` | The boards in intake order, whether the order is `derived` or `explicit`, the evaluator in use with `evaluatorSource` (`env`, `project`, or `legacy` for a project with no setting) and the project's own `projectEvaluator`, and a comparison of both evaluators over the project's newest 200 items against that order (`compared`, `differing`, `notRouted`), worked out on every read. |
1064
+ | `PUT /web/factory/projects/:id/intake-order` | `{ boardKeys }`, every board once (a missing or extra board is refused with `intake_order_set_mismatch` (409), a repeated one with `invalid_intake_route` (422)); and/or `{ evaluator }`, `intake-order` or `route-list`. Admin only. Every accepted `boardKeys` request is audited as `factory.intake_order.updated`, even when the order is unchanged; an evaluator change as `factory.intake_order.evaluator_updated` with `{ before, after }`, and not at all when the evaluator is unchanged. |
1065
+ | `GET /web/factory/projects/:id/intake/not-routed` | Items no board took and nobody has filed since, oldest first, with the reason. Paged: `limit` (default 50, at most 100) and `cursor`, the `nextCursor` of the page before (null on the last). |
1066
+ | `POST /web/factory/projects/:id/intake/not-routed/:decisionId/route-again` | Runs intake for the item again, by intake order whichever evaluator the replica runs. Refused with `intake_not_routed` (422) while no board's rules take it; otherwise 202, and the dispatcher files it where the rules say. Admin only; audited as `factory.intake.routed_again`. |
1067
+ | `GET /web/factory/projects/:id/intake/skipped` | Each card-move rule that matched but was skipped because its target couldn't take the card, in the last 30 days: `routeId`, `count`, and the newest skip as `latest`. |
1038
1068
 
1039
1069
  Every arrival's decision (placed or Not routed) is recorded under both evaluators. Once a card is filed for an item, by Route again or by a later delivery a fixed rule takes, its Not routed record is resolved and leaves the list.
1040
1070
 
@@ -1118,14 +1148,14 @@ The message never carries the comment's body or the issue's title: the session f
1118
1148
 
1119
1149
  **Routes.** Reading needs a signed-in user of the project's organization. Changes need an organization admin when auth is enabled. Deleting or reordering routes renumbers the routes after it and bumps their `revision`, so an update sent with an older `expectedRevision` is refused with 409 and must be retried with the current one. Changes are recorded in the audit log as `factory.intake_route.created`, `updated`, `deleted` and `reordered`.
1120
1150
 
1121
- | Method | Path | Body | Result |
1122
- | -------- | --------------------------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1123
- | `GET` | `/web/factory/projects/:id/intake-routes` | — | `intakeRoutes` in order. |
1124
- | `GET` | `/web/factory/projects/:id/intake-routes/:routeId` | — | The route. |
1125
- | `POST` | `/web/factory/projects/:id/intake-routes` | The route. | `201` and the route, added at the end. `422 unknown_board`, `unknown_phase`, `terminal_phase` or `unreachable_phase` for a target cards can't land on; `422 invalid_intake_route` for a bad `on` or a `when` testing `event.*` on a placement-only route. `409 intake_route_limit` past 100 routes. |
1126
- | `PATCH` | `/web/factory/projects/:id/intake-routes/:routeId` | The fields to change, plus `expectedRevision`. | The route. |
1127
- | `DELETE` | `/web/factory/projects/:id/intake-routes/:routeId?expectedRevision=n` | — | `204`. |
1128
- | `POST` | `/web/factory/projects/:id/intake-routes/reorder` | `{ "ids": [...] }`: every route of the project, once each. | The routes in their new order. `409 intake_route_set_mismatch` if the list differs from the project's routes. |
1151
+ | Method | Path | Body | Result |
1152
+ | -------- | --------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1153
+ | `GET` | `/web/factory/projects/:id/intake-routes` | — | `intakeRoutes` in order. |
1154
+ | `GET` | `/web/factory/projects/:id/intake-routes/:routeId` | — | The route. |
1155
+ | `POST` | `/web/factory/projects/:id/intake-routes` | The route. | `201` and the route, added at the end. `422 unknown_board`, `unknown_phase` or `terminal_phase` for a target cards can't land on; `422 invalid_intake_route` for a bad `on` or a `when` testing `event.*` on a placement-only route. `409 intake_route_limit` past 100 routes. |
1156
+ | `PATCH` | `/web/factory/projects/:id/intake-routes/:routeId` | The fields to change, plus `expectedRevision`. | The route. |
1157
+ | `DELETE` | `/web/factory/projects/:id/intake-routes/:routeId?expectedRevision=n` | — | `204`. |
1158
+ | `POST` | `/web/factory/projects/:id/intake-routes/reorder` | `{ "ids": [...] }`: every route of the project, once each. | The routes in their new order. `409 intake_route_set_mismatch` if the list differs from the project's routes. |
1129
1159
 
1130
1160
  A stale `expectedRevision` is refused with `409 revision_mismatch`. Each route reports `problems`, for example when its board has since been deleted. Such a route places no cards.
1131
1161
 
@@ -63,6 +63,22 @@ export declare function combineUpdates(events: readonly BoardEventFacts[]): Boar
63
63
  */
64
64
  export type PullRequestEvent = Extract<StatusEvent, `pull_request.${string}`>;
65
65
  export declare function isPullRequestEvent(type: StatusEvent): type is PullRequestEvent;
66
+ /** Merging or closing settles a pull request whoever its author is, so those events always move the card. */
67
+ export declare const SETTLING_PULL_REQUEST_EVENTS: ReadonlySet<string>;
68
+ /** Whether any condition in the group, however nested, asks about the field. */
69
+ export declare function testsField(group: RuleGroup | null, field: string): boolean;
70
+ /**
71
+ * Whether every way the group can match demands a trusted pull request author: one of an AND's
72
+ * conditions requires it, or every branch of an OR does. Presence alone is not enough — an OR
73
+ * that names `pullRequest.trusted` in one branch still matches an outside author through another.
74
+ */
75
+ export declare function requiresTrustedPullRequest(group: RuleGroup | null): boolean;
76
+ /**
77
+ * Whether a rule's card moves would also act for outside authors' pull requests: it listens on a
78
+ * pull request event that doesn't settle one, and its conditions don't demand a trusted author on
79
+ * every path a card can match through.
80
+ */
81
+ export declare function matchesOutsiderPullRequests(on: readonly string[], when: RuleGroup | null): boolean;
66
82
  /**
67
83
  * Whether the event may move a card that is, or isn't, finished: a reopen moves only a finished
68
84
  * card, a close or a merge only an unfinished one. A push or a review request re-reviews a pull
@@ -89,6 +105,13 @@ export interface BoardEventFacts {
89
105
  pullRequest?: string;
90
106
  /** On a pull request event: whether that pull request's author has write access (or is Factory). */
91
107
  pullRequestTrusted?: boolean;
108
+ /**
109
+ * On a pull request event: whether the person who caused the event has write access (or is
110
+ * Factory). A maintainer acting on an outside author's pull request vouches for the work they
111
+ * trigger, so run approval reads this, never the author's trust. Unset means unknown — a polled
112
+ * or system delivery — which counts as untrusted.
113
+ */
114
+ actorTrusted?: boolean;
92
115
  /**
93
116
  * On the `pull_request.opened` a pull request linking to the card of the issue it closes brings:
94
117
  * that card as it was before the pull request joined it (see `closedIssueRuleFacts`).
@@ -1 +1 @@
1
- {"version":3,"file":"board-events.d.ts","sourceRoot":"","sources":["../../src/boards/board-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wB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AS,UAAU,EAA2B,CAAC;AAElF,8DAA8D;AAC9D,eAAO,MAAM,kBAAkB,YAC7B,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,EACvB,yBAAyB,CACjB,CAAC;AAEX,qFAAqF;AACrF,eAAO,MAAM,iBAAiB,2IAAiE,CAAC;AAEhG,4EAA4E;AAC5E,eAAO,MAAM,qBAAqB,YAAI,YAAY,CAAU,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,YACnC,yBAAyB,EACzB,mBAAmB,EACnB,4BAA4B,CACpB,CAAC;AAEX,qDAAqD;AACrD,eAAO,MAAM,wBAAwB,+eAK3B,CAAC;AAEX;;;GAGG;AACH,eAAO,MAAM,kBAAkB,yLAQrB,CAAC;AAEX,iFAAiF;AACjF,eAAO,MAAM,kBAAkB,ggBAE9B,CAAC;AAqBF;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAsB/F"}
@@ -125,15 +125,49 @@ function combineUpdates(events) {
125
125
  ...combined,
126
126
  pullRequest: first.pullRequest
127
127
  } : combined;
128
- if (events.some((event) => event.pullRequestTrusted === void 0)) return identified;
129
- return {
128
+ const folded = events.some((event) => event.actorTrusted === void 0) ? identified : {
130
129
  ...identified,
130
+ actorTrusted: events.every((event) => event.actorTrusted === true)
131
+ };
132
+ if (events.some((event) => event.pullRequestTrusted === void 0)) return folded;
133
+ return {
134
+ ...folded,
131
135
  pullRequestTrusted: events.every((event) => event.pullRequestTrusted === true)
132
136
  };
133
137
  }
134
138
  function isPullRequestEvent(type) {
135
139
  return type.startsWith("pull_request.");
136
140
  }
141
+ /** Merging or closing settles a pull request whoever its author is, so those events always move the card. */
142
+ const SETTLING_PULL_REQUEST_EVENTS = /* @__PURE__ */ new Set(["pull_request.merged", "pull_request.closed"]);
143
+ /** Whether any condition in the group, however nested, asks about the field. */
144
+ function testsField(group, field) {
145
+ return group?.conditions.some((member) => "field" in member ? member.field === field : testsField(member, field)) ?? false;
146
+ }
147
+ /** Whether the one condition only lets a trusted author's pull request through. */
148
+ function requiresTrust(condition) {
149
+ if (condition.field !== "pullRequest.trusted") return false;
150
+ return condition.operator === "equals" && condition.value === true || condition.operator === "not_equals" && condition.value === false;
151
+ }
152
+ /**
153
+ * Whether every way the group can match demands a trusted pull request author: one of an AND's
154
+ * conditions requires it, or every branch of an OR does. Presence alone is not enough — an OR
155
+ * that names `pullRequest.trusted` in one branch still matches an outside author through another.
156
+ */
157
+ function requiresTrustedPullRequest(group) {
158
+ if (!group) return false;
159
+ const requires = (member) => "field" in member ? requiresTrust(member) : requiresTrustedPullRequest(member);
160
+ if (group.operator === "OR") return group.conditions.length > 0 && group.conditions.every(requires);
161
+ return group.conditions.some(requires);
162
+ }
163
+ /**
164
+ * Whether a rule's card moves would also act for outside authors' pull requests: it listens on a
165
+ * pull request event that doesn't settle one, and its conditions don't demand a trusted author on
166
+ * every path a card can match through.
167
+ */
168
+ function matchesOutsiderPullRequests(on, when) {
169
+ return on.some((event) => event.startsWith("pull_request.") && !SETTLING_PULL_REQUEST_EVENTS.has(event)) && !requiresTrustedPullRequest(when);
170
+ }
137
171
  /**
138
172
  * Whether the event may move a card that is, or isn't, finished: a reopen moves only a finished
139
173
  * card, a close or a merge only an unfinished one. A push or a review request re-reviews a pull
@@ -245,6 +279,6 @@ function routeEventsProblem(on, when) {
245
279
  if (when && !on.includes("work_item.closed") && namesField(when, ["event.reason"])) return "`event.reason` only applies to routes that handle work_item.closed: no other event carries a reason.";
246
280
  return null;
247
281
  }
248
- export { ACTIVITY_EVENTS, CARD_MOVE_RULE_FIELDS, CHANGE_RULE_FIELDS, CLOSED_ISSUE_RULE_FIELDS, CLOSE_REASONS, DEFAULT_ROUTE_EVENTS, EVENT_RULE_FIELDS, INTAKE_ROUTE_RULE_FIELDS, LEGACY_ARRIVAL_EVENT, LEGACY_RULE_FIELDS, PICKER_RULE_FIELDS, ROUTE_EVENTS, STATUS_EVENTS, UPDATE_EVENTS, arrivalKind, arrivalKinds, closeReason, combineChanges, combineUpdates, eventMovesCard, eventRuleFacts, isPullRequestEvent, isUpdateEvent, listChange, routeEventsProblem, updateEventFacts };
282
+ export { ACTIVITY_EVENTS, CARD_MOVE_RULE_FIELDS, CHANGE_RULE_FIELDS, CLOSED_ISSUE_RULE_FIELDS, CLOSE_REASONS, DEFAULT_ROUTE_EVENTS, EVENT_RULE_FIELDS, INTAKE_ROUTE_RULE_FIELDS, LEGACY_ARRIVAL_EVENT, LEGACY_RULE_FIELDS, PICKER_RULE_FIELDS, ROUTE_EVENTS, SETTLING_PULL_REQUEST_EVENTS, STATUS_EVENTS, UPDATE_EVENTS, arrivalKind, arrivalKinds, closeReason, combineChanges, combineUpdates, eventMovesCard, eventRuleFacts, isPullRequestEvent, isUpdateEvent, listChange, matchesOutsiderPullRequests, requiresTrustedPullRequest, routeEventsProblem, testsField, updateEventFacts };
249
283
 
250
284
  //# sourceMappingURL=board-events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"board-events.js","names":[],"sources":["../../src/boards/board-events.ts"],"sourcesContent":["import type { RuleGroup } from '../rules/rule-group.js';\nimport { CARD_RULE_FIELDS } from '../rules/rule-group.js';\nimport { AUTO_TRIAGED_LABEL, NEEDS_APPROVAL_LABEL } from '../rules/types.js';\n\n/**\n * What happened to a card's source, named the same for every provider. Integrations map their\n * webhooks onto these. Status events change where a card belongs: only these can move a card, so\n * only these may be named in a route's `on`.\n */\nexport const STATUS_EVENTS = [\n 'work_item.opened',\n 'work_item.reopened',\n 'work_item.updated',\n 'work_item.closed',\n 'pull_request.opened',\n 'pull_request.reopened',\n 'pull_request.updated',\n 'pull_request.synchronized',\n 'pull_request.review_requested',\n 'pull_request.merged',\n 'pull_request.closed',\n] as const;\nexport type StatusEvent = (typeof STATUS_EVENTS)[number];\n\n/**\n * The event routes placed new cards on before issues and pull requests had events of their own: an\n * issue or a pull request with no card opened. It never fires and never moves a card. A stored\n * route naming it, or naming no event, keeps filing both for good, and the API keeps accepting and\n * returning it, so editing such a route never narrows it.\n */\nexport const LEGACY_ARRIVAL_EVENT = 'work_item.created';\n\n/** What a route's `on` may name: the status events, and the legacy arrival event. */\nexport const ROUTE_EVENTS = [...STATUS_EVENTS, LEGACY_ARRIVAL_EVENT] as const;\nexport type RouteEvent = (typeof ROUTE_EVENTS)[number];\n\n/** What an arrival is: an issue (any provider's work item) or a pull request with no card. */\nexport type ArrivalKind = 'issue' | 'pull_request';\n\n/** The kind of an arrival, read from its `source.kind` fact. */\nexport function arrivalKind(facts: Record<string, unknown>): ArrivalKind {\n return facts['source.kind'] === 'pull_request' ? 'pull_request' : 'issue';\n}\n\n/** What a route's arrival events mean: a route stored by 0.28 moved cards on `pull_request.opened` and filed none. */\nexport interface RouteArrivals {\n on: readonly string[];\n /** True on a route stored before `pull_request.opened` filed pull requests: there it only moves a card. */\n pullRequestOpenedMovesOnly?: boolean;\n}\n\n/** The arrivals a route files: issues on `work_item.opened`, pull requests on `pull_request.opened`, both on `work_item.created`. */\nexport function arrivalKinds({ on, pullRequestOpenedMovesOnly }: RouteArrivals): Set<ArrivalKind> {\n const kinds = new Set<ArrivalKind>();\n if (on.includes('work_item.opened') || on.includes(LEGACY_ARRIVAL_EVENT)) kinds.add('issue');\n if ((on.includes('pull_request.opened') && !pullRequestOpenedMovesOnly) || on.includes(LEGACY_ARRIVAL_EVENT)) {\n kinds.add('pull_request');\n }\n return kinds;\n}\n\n/** Labels or assignees an update added and removed. */\nexport interface ItemChange {\n added: string[];\n removed: string[];\n}\n\n/**\n * Folds several changes, oldest first, into the net change: a label added then removed (or removed\n * then added back) cancels out, so the result never carries just the newest delta.\n */\nexport function combineChanges(changes: readonly ItemChange[]): ItemChange {\n // Keyed case-insensitively like `listChange`, keeping the newest spelling.\n const net = new Map<string, { name: string; side: 'added' | 'removed' }>();\n const fold = (name: string, side: 'added' | 'removed') => {\n const key = name.toLowerCase();\n const seen = net.get(key);\n if (seen && seen.side !== side) net.delete(key);\n else net.set(key, { name, side });\n };\n for (const change of changes) {\n for (const name of change.removed) fold(name, 'removed');\n for (const name of change.added) fold(name, 'added');\n }\n const pick = (side: 'added' | 'removed') =>\n [...net.values()].filter(entry => entry.side === side).map(entry => entry.name);\n return { added: pick('added'), removed: pick('removed') };\n}\n\n/** The change between two lists (compared case-insensitively, keeping the newer spelling). */\nexport function listChange(before: readonly string[], after: readonly string[]): ItemChange {\n const key = (value: string) => value.toLowerCase();\n const had = new Set(before.map(key));\n const has = new Set(after.map(key));\n return {\n added: after.filter(value => !had.has(key(value))),\n removed: before.filter(value => !has.has(key(value))),\n };\n}\n\nfunction changed(change: ItemChange | undefined): boolean {\n return Boolean(change && (change.added.length > 0 || change.removed.length > 0));\n}\n\n/** The events that report labels or assignees changing on the card's work item or pull request. */\nexport const UPDATE_EVENTS = ['work_item.updated', 'pull_request.updated'] as const;\nexport type UpdateEvent = (typeof UPDATE_EVENTS)[number];\n\nexport function isUpdateEvent(type: string): type is UpdateEvent {\n return (UPDATE_EVENTS as readonly string[]).includes(type);\n}\n\n/**\n * Labels Factory sets and clears itself to track triage and acceptance. Like a rule's own move,\n * changing them is bookkeeping, so they never count as a change, whoever made it.\n */\nconst FACTORY_MANAGED_LABELS = new Set([NEEDS_APPROVAL_LABEL, AUTO_TRIAGED_LABEL]);\n\nfunction withoutManagedLabels(change: ItemChange | undefined): ItemChange | undefined {\n if (!change) return undefined;\n const kept = (names: readonly string[]) => names.filter(name => !FACTORY_MANAGED_LABELS.has(name.toLowerCase()));\n return { added: kept(change.added), removed: kept(change.removed) };\n}\n\n/**\n * The update event for a change of labels and assignees, or undefined when nothing changed: an\n * item that reports \"changed\" without a label or assignee difference produces no event, and\n * neither does a change to only the labels Factory manages.\n */\nexport function updateEventFacts(\n type: UpdateEvent,\n { assignees, ...rest }: { labels?: ItemChange; assignees?: ItemChange },\n): BoardEventFacts | undefined {\n const change = { labels: withoutManagedLabels(rest.labels), assignees };\n if (!changed(change.labels) && !changed(change.assignees)) return undefined;\n return {\n type,\n ...(changed(change.labels) ? { labels: change.labels } : {}),\n ...(changed(change.assignees) ? { assignees: change.assignees } : {}),\n };\n}\n\n/** One update event standing for several, oldest first, or undefined when they cancel out. */\nexport function combineUpdates(events: readonly BoardEventFacts[]): BoardEventFacts | undefined {\n const [first] = events;\n if (!first || !isUpdateEvent(first.type)) return undefined;\n const combined = updateEventFacts(first.type, {\n labels: combineChanges(events.flatMap(event => (event.labels ? [event.labels] : []))),\n assignees: combineChanges(events.flatMap(event => (event.assignees ? [event.assignees] : []))),\n });\n if (!combined) return undefined;\n const identified = first.pullRequest !== undefined ? { ...combined, pullRequest: first.pullRequest } : combined;\n // The folded change stands for every pull request in it, so it is trusted only when each one is.\n if (events.some(event => event.pullRequestTrusted === undefined)) return identified;\n return { ...identified, pullRequestTrusted: events.every(event => event.pullRequestTrusted === true) };\n}\n\n/**\n * What happened to a card's pull request (GitHub) or merge request (GitLab): opened by the card's\n * session, pushed to, re-review requested, merged, or closed unmerged. A provider's default rule\n * decides whether the event moves the card at all; a route on the card's board naming the event\n * decides where it goes.\n */\nexport type PullRequestEvent = Extract<StatusEvent, `pull_request.${string}`>;\n\nexport function isPullRequestEvent(type: StatusEvent): type is PullRequestEvent {\n return type.startsWith('pull_request.');\n}\n\n/**\n * Whether the event may move a card that is, or isn't, finished: a reopen moves only a finished\n * card, a close or a merge only an unfinished one. A push or a review request re-reviews a pull\n * request whatever its card's phase, and an update or a pull request reopening moves the card\n * wherever a route sends it.\n */\nexport function eventMovesCard(type: StatusEvent, finished: boolean): boolean {\n switch (type) {\n case 'work_item.reopened':\n return finished;\n case 'work_item.closed':\n case 'pull_request.merged':\n case 'pull_request.closed':\n return !finished;\n default:\n return true;\n }\n}\n\n/** Activity on a card: it never moves the card, it only tells the card's session. */\nexport const ACTIVITY_EVENTS = ['work_item.commented', 'work_item.edited'] as const;\nexport type ActivityEvent = (typeof ACTIVITY_EVENTS)[number];\n\n/** Why a work item closed: `canceled` covers \"not planned\" and duplicates. */\nexport const CLOSE_REASONS = ['completed', 'canceled'] as const;\nexport type CloseReason = (typeof CLOSE_REASONS)[number];\n\n/** A status event as routes see it. Update events carry what changed. */\nexport interface BoardEventFacts {\n type: StatusEvent;\n reason?: CloseReason;\n labels?: ItemChange;\n assignees?: ItemChange;\n /**\n * On a pull request's update: which pull request changed (its source's external id), so changes\n * to two pull requests on one card never net out against each other.\n */\n pullRequest?: string;\n /** On a pull request event: whether that pull request's author has write access (or is Factory). */\n pullRequestTrusted?: boolean;\n /**\n * On the `pull_request.opened` a pull request linking to the card of the issue it closes brings:\n * that card as it was before the pull request joined it (see `closedIssueRuleFacts`).\n */\n closedIssue?: { phase: string | null; hasPullRequest: boolean };\n}\n\n/** The facts a route's `when` reads from an event. */\nexport function eventRuleFacts(event: BoardEventFacts): Record<string, unknown> {\n return {\n 'event.type': event.type,\n 'event.reason': event.reason,\n 'event.labels.added': event.labels?.added,\n 'event.labels.removed': event.labels?.removed,\n 'event.assignees.added': event.assignees?.added,\n 'event.assignees.removed': event.assignees?.removed,\n };\n}\n\n/** The close reason for a provider's own closed-state fact. */\nexport function closeReason(canceled: boolean): CloseReason {\n return canceled ? 'canceled' : 'completed';\n}\n\n/** What a route without `on` handles: placing new cards, issues and pull requests alike, as routes always have. */\nexport const DEFAULT_ROUTE_EVENTS: readonly RouteEvent[] = [LEGACY_ARRIVAL_EVENT];\n\n/** What an update changed: only update events carry these. */\nexport const CHANGE_RULE_FIELDS = [\n 'event.labels.added',\n 'event.labels.removed',\n 'event.assignees.added',\n 'event.assignees.removed',\n] as const;\n\n/** Facts a route's `when` can test about the event, besides the card's own facts. */\nexport const EVENT_RULE_FIELDS = ['event.type', 'event.reason', ...CHANGE_RULE_FIELDS] as const;\n\n/** Facts about the card an event would move; a new item has no card yet. */\nexport const CARD_MOVE_RULE_FIELDS = ['card.phase'] as const;\n\n/**\n * Facts a route can test about the issue an arriving pull request closes (see\n * `closedIssueRuleFacts`). Only arrivals have them, so phase conditions can't name them.\n */\nexport const CLOSED_ISSUE_RULE_FIELDS = [\n 'pullRequest.closesIssue',\n 'closedIssue.phase',\n 'closedIssue.hasPullRequest',\n] as const;\n\n/** Every field an intake route's `when` may name. */\nexport const INTAKE_ROUTE_RULE_FIELDS = [\n ...CARD_RULE_FIELDS,\n ...CARD_MOVE_RULE_FIELDS,\n ...EVENT_RULE_FIELDS,\n ...CLOSED_ISSUE_RULE_FIELDS,\n] as const;\n\n/**\n * Fields a stored route may still name and that keep evaluating, but the filter picker no longer\n * offers; the picker shows them as \"Legacy filter\" with a remove button.\n */\nexport const LEGACY_RULE_FIELDS = [\n 'item.key',\n 'item.title',\n 'item.state',\n 'source.integration',\n 'item.pullRequest',\n 'event.type',\n ...CLOSED_ISSUE_RULE_FIELDS,\n] as const;\n\n/** The one filter set the picker offers: every route field that isn't legacy. */\nexport const PICKER_RULE_FIELDS = INTAKE_ROUTE_RULE_FIELDS.filter(\n field => !(LEGACY_RULE_FIELDS as readonly string[]).includes(field),\n);\n\nfunction isStatusEvent(value: string): value is StatusEvent {\n return (STATUS_EVENTS as readonly string[]).includes(value);\n}\n\nfunction isRouteEvent(value: string): value is RouteEvent {\n return (ROUTE_EVENTS as readonly string[]).includes(value);\n}\n\n/** Events that only file new cards, so carry no event facts: `pull_request.opened` also moves cards. */\nfunction onlyFilesNewCards(event: string): boolean {\n return event === 'work_item.opened' || event === LEGACY_ARRIVAL_EVENT;\n}\n\nfunction namesField(group: RuleGroup, fields: readonly string[]): boolean {\n return group.conditions.some(condition =>\n 'conditions' in condition ? namesField(condition, fields) : fields.includes(condition.field),\n );\n}\n\n/**\n * Why a route's `on` and `when` can't be saved together, or null. `on` must name at least one\n * route event, each once; `event.*` conditions need an event besides `work_item.opened` and\n * `work_item.created`, which place new cards and carry no event facts, and `event.reason` needs `work_item.closed`, the\n * only event with a reason.\n */\nexport function routeEventsProblem(on: readonly string[], when: RuleGroup | null): string | null {\n if (on.length === 0) return '`on` must name at least one event.';\n if (new Set(on).size !== on.length) return '`on` may name each event only once.';\n for (const event of on) {\n if ((ACTIVITY_EVENTS as readonly string[]).includes(event)) {\n return `\"${event}\" is activity, not a status change: it notifies the card's session and can't move a card, so a route can't name it.`;\n }\n if (!isRouteEvent(event)) return `\"${event}\" is not a board event; use one of ${ROUTE_EVENTS.join(', ')}.`;\n }\n if (when && on.every(onlyFilesNewCards) && namesField(when, EVENT_RULE_FIELDS)) {\n return '`event.*` filters only apply to routes that handle an event besides work_item.opened and work_item.created.';\n }\n if (when && on.every(onlyFilesNewCards) && namesField(when, CARD_MOVE_RULE_FIELDS)) {\n return '`card.phase` only applies to routes that move an existing card: a new item has no card yet.';\n }\n if (when && !on.some(isUpdateEvent) && namesField(when, CHANGE_RULE_FIELDS)) {\n return 'What changed (`event.labels.*`, `event.assignees.*`) only applies to routes that handle work_item.updated or pull_request.updated.';\n }\n if (when && !on.includes('work_item.closed') && namesField(when, ['event.reason'])) {\n return '`event.reason` only applies to routes that handle work_item.closed: no other event carries a reason.';\n }\n return null;\n}\n"],"mappings":";;;;;;;;AASA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AASA,MAAa,uBAAuB;;AAGpC,MAAa,eAAe,CAAC,GAAG,eAAe,oBAAoB;;AAOnE,SAAgB,YAAY,OAA6C;CACvE,OAAO,MAAM,mBAAmB,iBAAiB,iBAAiB;AACpE;;AAUA,SAAgB,aAAa,EAAE,IAAI,8BAA+D;CAChG,MAAM,wBAAQ,IAAI,IAAiB;CACnC,IAAI,GAAG,SAAS,kBAAkB,KAAK,GAAG,SAAA,mBAA6B,GAAG,MAAM,IAAI,OAAO;CAC3F,IAAK,GAAG,SAAS,qBAAqB,KAAK,CAAC,8BAA+B,GAAG,SAAA,mBAA6B,GACzG,MAAM,IAAI,cAAc;CAE1B,OAAO;AACT;;;;;AAYA,SAAgB,eAAe,SAA4C;CAEzE,MAA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,YAAY,WAAW,WAAW,MAAM,IAAI,OAAO,SAAS,UAAU,KAAK,CAC7F;AACF;;;;;;;AAQA,SAAgB,mBAAmB,IAAuB,MAAuC;CAC/F,IAAI,GAAG,WAAW,GAAG,OAAO;CAC5B,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,SAAS,GAAG,QAAQ,OAAO;CAC3C,KAAK,MAAM,SAAS,IAAI;EACtB,IAAK,gBAAsC,SAAS,KAAK,GACvD,OAAO,IAAI,MAAM;EAEnB,IAAI,CAAC,aAAa,KAAK,GAAG,OAAO,IAAI,MAAM,qCAAqC,aAAa,KAAK,IAAI,EAAE;CAC1G;CACA,IAAI,QAAQ,GAAG,MAAM,iBAAiB,KAAK,WAAW,MAAM,iBAAiB,GAC3E,OAAO;CAET,IAAI,QAAQ,GAAG,MAAM,iBAAiB,KAAK,WAAW,MAAM,qBAAqB,GAC/E,OAAO;CAET,IAAI,QAAQ,CAAC,GAAG,KAAK,aAAa,KAAK,WAAW,MAAM,kBAAkB,GACxE,OAAO;CAET,IAAI,QAAQ,CAAC,GAAG,SAAS,kBAAkB,KAAK,WAAW,MAAM,CAAC,cAAc,CAAC,GAC/E,OAAO;CAET,OAAO;AACT"}
1
+ {"version":3,"file":"board-events.js","names":[],"sources":["../../src/boards/board-events.ts"],"sourcesContent":["import type { RuleCondition, RuleGroup } from '../rules/rule-group.js';\nimport { CARD_RULE_FIELDS } from '../rules/rule-group.js';\nimport { AUTO_TRIAGED_LABEL, NEEDS_APPROVAL_LABEL } from '../rules/types.js';\n\n/**\n * What happened to a card's source, named the same for every provider. Integrations map their\n * webhooks onto these. Status events change where a card belongs: only these can move a card, so\n * only these may be named in a route's `on`.\n */\nexport const STATUS_EVENTS = [\n 'work_item.opened',\n 'work_item.reopened',\n 'work_item.updated',\n 'work_item.closed',\n 'pull_request.opened',\n 'pull_request.reopened',\n 'pull_request.updated',\n 'pull_request.synchronized',\n 'pull_request.review_requested',\n 'pull_request.merged',\n 'pull_request.closed',\n] as const;\nexport type StatusEvent = (typeof STATUS_EVENTS)[number];\n\n/**\n * The event routes placed new cards on before issues and pull requests had events of their own: an\n * issue or a pull request with no card opened. It never fires and never moves a card. A stored\n * route naming it, or naming no event, keeps filing both for good, and the API keeps accepting and\n * returning it, so editing such a route never narrows it.\n */\nexport const LEGACY_ARRIVAL_EVENT = 'work_item.created';\n\n/** What a route's `on` may name: the status events, and the legacy arrival event. */\nexport const ROUTE_EVENTS = [...STATUS_EVENTS, LEGACY_ARRIVAL_EVENT] as const;\nexport type RouteEvent = (typeof ROUTE_EVENTS)[number];\n\n/** What an arrival is: an issue (any provider's work item) or a pull request with no card. */\nexport type ArrivalKind = 'issue' | 'pull_request';\n\n/** The kind of an arrival, read from its `source.kind` fact. */\nexport function arrivalKind(facts: Record<string, unknown>): ArrivalKind {\n return facts['source.kind'] === 'pull_request' ? 'pull_request' : 'issue';\n}\n\n/** What a route's arrival events mean: a route stored by 0.28 moved cards on `pull_request.opened` and filed none. */\nexport interface RouteArrivals {\n on: readonly string[];\n /** True on a route stored before `pull_request.opened` filed pull requests: there it only moves a card. */\n pullRequestOpenedMovesOnly?: boolean;\n}\n\n/** The arrivals a route files: issues on `work_item.opened`, pull requests on `pull_request.opened`, both on `work_item.created`. */\nexport function arrivalKinds({ on, pullRequestOpenedMovesOnly }: RouteArrivals): Set<ArrivalKind> {\n const kinds = new Set<ArrivalKind>();\n if (on.includes('work_item.opened') || on.includes(LEGACY_ARRIVAL_EVENT)) kinds.add('issue');\n if ((on.includes('pull_request.opened') && !pullRequestOpenedMovesOnly) || on.includes(LEGACY_ARRIVAL_EVENT)) {\n kinds.add('pull_request');\n }\n return kinds;\n}\n\n/** Labels or assignees an update added and removed. */\nexport interface ItemChange {\n added: string[];\n removed: string[];\n}\n\n/**\n * Folds several changes, oldest first, into the net change: a label added then removed (or removed\n * then added back) cancels out, so the result never carries just the newest delta.\n */\nexport function combineChanges(changes: readonly ItemChange[]): ItemChange {\n // Keyed case-insensitively like `listChange`, keeping the newest spelling.\n const net = new Map<string, { name: string; side: 'added' | 'removed' }>();\n const fold = (name: string, side: 'added' | 'removed') => {\n const key = name.toLowerCase();\n const seen = net.get(key);\n if (seen && seen.side !== side) net.delete(key);\n else net.set(key, { name, side });\n };\n for (const change of changes) {\n for (const name of change.removed) fold(name, 'removed');\n for (const name of change.added) fold(name, 'added');\n }\n const pick = (side: 'added' | 'removed') =>\n [...net.values()].filter(entry => entry.side === side).map(entry => entry.name);\n return { added: pick('added'), removed: pick('removed') };\n}\n\n/** The change between two lists (compared case-insensitively, keeping the newer spelling). */\nexport function listChange(before: readonly string[], after: readonly string[]): ItemChange {\n const key = (value: string) => value.toLowerCase();\n const had = new Set(before.map(key));\n const has = new Set(after.map(key));\n return {\n added: after.filter(value => !had.has(key(value))),\n removed: before.filter(value => !has.has(key(value))),\n };\n}\n\nfunction changed(change: ItemChange | undefined): boolean {\n return Boolean(change && (change.added.length > 0 || change.removed.length > 0));\n}\n\n/** The events that report labels or assignees changing on the card's work item or pull request. */\nexport const UPDATE_EVENTS = ['work_item.updated', 'pull_request.updated'] as const;\nexport type UpdateEvent = (typeof UPDATE_EVENTS)[number];\n\nexport function isUpdateEvent(type: string): type is UpdateEvent {\n return (UPDATE_EVENTS as readonly string[]).includes(type);\n}\n\n/**\n * Labels Factory sets and clears itself to track triage and acceptance. Like a rule's own move,\n * changing them is bookkeeping, so they never count as a change, whoever made it.\n */\nconst FACTORY_MANAGED_LABELS = new Set([NEEDS_APPROVAL_LABEL, AUTO_TRIAGED_LABEL]);\n\nfunction withoutManagedLabels(change: ItemChange | undefined): ItemChange | undefined {\n if (!change) return undefined;\n const kept = (names: readonly string[]) => names.filter(name => !FACTORY_MANAGED_LABELS.has(name.toLowerCase()));\n return { added: kept(change.added), removed: kept(change.removed) };\n}\n\n/**\n * The update event for a change of labels and assignees, or undefined when nothing changed: an\n * item that reports \"changed\" without a label or assignee difference produces no event, and\n * neither does a change to only the labels Factory manages.\n */\nexport function updateEventFacts(\n type: UpdateEvent,\n { assignees, ...rest }: { labels?: ItemChange; assignees?: ItemChange },\n): BoardEventFacts | undefined {\n const change = { labels: withoutManagedLabels(rest.labels), assignees };\n if (!changed(change.labels) && !changed(change.assignees)) return undefined;\n return {\n type,\n ...(changed(change.labels) ? { labels: change.labels } : {}),\n ...(changed(change.assignees) ? { assignees: change.assignees } : {}),\n };\n}\n\n/** One update event standing for several, oldest first, or undefined when they cancel out. */\nexport function combineUpdates(events: readonly BoardEventFacts[]): BoardEventFacts | undefined {\n const [first] = events;\n if (!first || !isUpdateEvent(first.type)) return undefined;\n const combined = updateEventFacts(first.type, {\n labels: combineChanges(events.flatMap(event => (event.labels ? [event.labels] : []))),\n assignees: combineChanges(events.flatMap(event => (event.assignees ? [event.assignees] : []))),\n });\n if (!combined) return undefined;\n const identified = first.pullRequest !== undefined ? { ...combined, pullRequest: first.pullRequest } : combined;\n // The folded change stands for every pull request and every actor in it, so each trust tag\n // survives only when every event carries it, and holds only when each one holds.\n const folded = events.some(event => event.actorTrusted === undefined)\n ? identified\n : { ...identified, actorTrusted: events.every(event => event.actorTrusted === true) };\n if (events.some(event => event.pullRequestTrusted === undefined)) return folded;\n return { ...folded, pullRequestTrusted: events.every(event => event.pullRequestTrusted === true) };\n}\n\n/**\n * What happened to a card's pull request (GitHub) or merge request (GitLab): opened by the card's\n * session, pushed to, re-review requested, merged, or closed unmerged. A provider's default rule\n * decides whether the event moves the card at all; a route on the card's board naming the event\n * decides where it goes.\n */\nexport type PullRequestEvent = Extract<StatusEvent, `pull_request.${string}`>;\n\nexport function isPullRequestEvent(type: StatusEvent): type is PullRequestEvent {\n return type.startsWith('pull_request.');\n}\n\n/** Merging or closing settles a pull request whoever its author is, so those events always move the card. */\nexport const SETTLING_PULL_REQUEST_EVENTS: ReadonlySet<string> = new Set([\n 'pull_request.merged',\n 'pull_request.closed',\n]);\n\n/** Whether any condition in the group, however nested, asks about the field. */\nexport function testsField(group: RuleGroup | null, field: string): boolean {\n return (\n group?.conditions.some(member => ('field' in member ? member.field === field : testsField(member, field))) ?? false\n );\n}\n\n/** Whether the one condition only lets a trusted author's pull request through. */\nfunction requiresTrust(condition: RuleCondition): boolean {\n if (condition.field !== 'pullRequest.trusted') return false;\n return (\n (condition.operator === 'equals' && condition.value === true) ||\n (condition.operator === 'not_equals' && condition.value === false)\n );\n}\n\n/**\n * Whether every way the group can match demands a trusted pull request author: one of an AND's\n * conditions requires it, or every branch of an OR does. Presence alone is not enough — an OR\n * that names `pullRequest.trusted` in one branch still matches an outside author through another.\n */\nexport function requiresTrustedPullRequest(group: RuleGroup | null): boolean {\n if (!group) return false;\n const requires = (member: RuleGroup | RuleCondition): boolean =>\n 'field' in member ? requiresTrust(member) : requiresTrustedPullRequest(member);\n if (group.operator === 'OR') return group.conditions.length > 0 && group.conditions.every(requires);\n return group.conditions.some(requires);\n}\n\n/**\n * Whether a rule's card moves would also act for outside authors' pull requests: it listens on a\n * pull request event that doesn't settle one, and its conditions don't demand a trusted author on\n * every path a card can match through.\n */\nexport function matchesOutsiderPullRequests(on: readonly string[], when: RuleGroup | null): boolean {\n return (\n on.some(event => event.startsWith('pull_request.') && !SETTLING_PULL_REQUEST_EVENTS.has(event)) &&\n !requiresTrustedPullRequest(when)\n );\n}\n\n/**\n * Whether the event may move a card that is, or isn't, finished: a reopen moves only a finished\n * card, a close or a merge only an unfinished one. A push or a review request re-reviews a pull\n * request whatever its card's phase, and an update or a pull request reopening moves the card\n * wherever a route sends it.\n */\nexport function eventMovesCard(type: StatusEvent, finished: boolean): boolean {\n switch (type) {\n case 'work_item.reopened':\n return finished;\n case 'work_item.closed':\n case 'pull_request.merged':\n case 'pull_request.closed':\n return !finished;\n default:\n return true;\n }\n}\n\n/** Activity on a card: it never moves the card, it only tells the card's session. */\nexport const ACTIVITY_EVENTS = ['work_item.commented', 'work_item.edited'] as const;\nexport type ActivityEvent = (typeof ACTIVITY_EVENTS)[number];\n\n/** Why a work item closed: `canceled` covers \"not planned\" and duplicates. */\nexport const CLOSE_REASONS = ['completed', 'canceled'] as const;\nexport type CloseReason = (typeof CLOSE_REASONS)[number];\n\n/** A status event as routes see it. Update events carry what changed. */\nexport interface BoardEventFacts {\n type: StatusEvent;\n reason?: CloseReason;\n labels?: ItemChange;\n assignees?: ItemChange;\n /**\n * On a pull request's update: which pull request changed (its source's external id), so changes\n * to two pull requests on one card never net out against each other.\n */\n pullRequest?: string;\n /** On a pull request event: whether that pull request's author has write access (or is Factory). */\n pullRequestTrusted?: boolean;\n /**\n * On a pull request event: whether the person who caused the event has write access (or is\n * Factory). A maintainer acting on an outside author's pull request vouches for the work they\n * trigger, so run approval reads this, never the author's trust. Unset means unknown — a polled\n * or system delivery — which counts as untrusted.\n */\n actorTrusted?: boolean;\n /**\n * On the `pull_request.opened` a pull request linking to the card of the issue it closes brings:\n * that card as it was before the pull request joined it (see `closedIssueRuleFacts`).\n */\n closedIssue?: { phase: string | null; hasPullRequest: boolean };\n}\n\n/** The facts a route's `when` reads from an event. */\nexport function eventRuleFacts(event: BoardEventFacts): Record<string, unknown> {\n return {\n 'event.type': event.type,\n 'event.reason': event.reason,\n 'event.labels.added': event.labels?.added,\n 'event.labels.removed': event.labels?.removed,\n 'event.assignees.added': event.assignees?.added,\n 'event.assignees.removed': event.assignees?.removed,\n };\n}\n\n/** The close reason for a provider's own closed-state fact. */\nexport function closeReason(canceled: boolean): CloseReason {\n return canceled ? 'canceled' : 'completed';\n}\n\n/** What a route without `on` handles: placing new cards, issues and pull requests alike, as routes always have. */\nexport const DEFAULT_ROUTE_EVENTS: readonly RouteEvent[] = [LEGACY_ARRIVAL_EVENT];\n\n/** What an update changed: only update events carry these. */\nexport const CHANGE_RULE_FIELDS = [\n 'event.labels.added',\n 'event.labels.removed',\n 'event.assignees.added',\n 'event.assignees.removed',\n] as const;\n\n/** Facts a route's `when` can test about the event, besides the card's own facts. */\nexport const EVENT_RULE_FIELDS = ['event.type', 'event.reason', ...CHANGE_RULE_FIELDS] as const;\n\n/** Facts about the card an event would move; a new item has no card yet. */\nexport const CARD_MOVE_RULE_FIELDS = ['card.phase'] as const;\n\n/**\n * Facts a route can test about the issue an arriving pull request closes (see\n * `closedIssueRuleFacts`). Only arrivals have them, so phase conditions can't name them.\n */\nexport const CLOSED_ISSUE_RULE_FIELDS = [\n 'pullRequest.closesIssue',\n 'closedIssue.phase',\n 'closedIssue.hasPullRequest',\n] as const;\n\n/** Every field an intake route's `when` may name. */\nexport const INTAKE_ROUTE_RULE_FIELDS = [\n ...CARD_RULE_FIELDS,\n ...CARD_MOVE_RULE_FIELDS,\n ...EVENT_RULE_FIELDS,\n ...CLOSED_ISSUE_RULE_FIELDS,\n] as const;\n\n/**\n * Fields a stored route may still name and that keep evaluating, but the filter picker no longer\n * offers; the picker shows them as \"Legacy filter\" with a remove button.\n */\nexport const LEGACY_RULE_FIELDS = [\n 'item.key',\n 'item.title',\n 'item.state',\n 'source.integration',\n 'item.pullRequest',\n 'event.type',\n ...CLOSED_ISSUE_RULE_FIELDS,\n] as const;\n\n/** The one filter set the picker offers: every route field that isn't legacy. */\nexport const PICKER_RULE_FIELDS = INTAKE_ROUTE_RULE_FIELDS.filter(\n field => !(LEGACY_RULE_FIELDS as readonly string[]).includes(field),\n);\n\nfunction isStatusEvent(value: string): value is StatusEvent {\n return (STATUS_EVENTS as readonly string[]).includes(value);\n}\n\nfunction isRouteEvent(value: string): value is RouteEvent {\n return (ROUTE_EVENTS as readonly string[]).includes(value);\n}\n\n/** Events that only file new cards, so carry no event facts: `pull_request.opened` also moves cards. */\nfunction onlyFilesNewCards(event: string): boolean {\n return event === 'work_item.opened' || event === LEGACY_ARRIVAL_EVENT;\n}\n\nfunction namesField(group: RuleGroup, fields: readonly string[]): boolean {\n return group.conditions.some(condition =>\n 'conditions' in condition ? namesField(condition, fields) : fields.includes(condition.field),\n );\n}\n\n/**\n * Why a route's `on` and `when` can't be saved together, or null. `on` must name at least one\n * route event, each once; `event.*` conditions need an event besides `work_item.opened` and\n * `work_item.created`, which place new cards and carry no event facts, and `event.reason` needs `work_item.closed`, the\n * only event with a reason.\n */\nexport function routeEventsProblem(on: readonly string[], when: RuleGroup | null): string | null {\n if (on.length === 0) return '`on` must name at least one event.';\n if (new Set(on).size !== on.length) return '`on` may name each event only once.';\n for (const event of on) {\n if ((ACTIVITY_EVENTS as readonly string[]).includes(event)) {\n return `\"${event}\" is activity, not a status change: it notifies the card's session and can't move a card, so a route can't name it.`;\n }\n if (!isRouteEvent(event)) return `\"${event}\" is not a board event; use one of ${ROUTE_EVENTS.join(', ')}.`;\n }\n if (when && on.every(onlyFilesNewCards) && namesField(when, EVENT_RULE_FIELDS)) {\n return '`event.*` filters only apply to routes that handle an event besides work_item.opened and work_item.created.';\n }\n if (when && on.every(onlyFilesNewCards) && namesField(when, CARD_MOVE_RULE_FIELDS)) {\n return '`card.phase` only applies to routes that move an existing card: a new item has no card yet.';\n }\n if (when && !on.some(isUpdateEvent) && namesField(when, CHANGE_RULE_FIELDS)) {\n return 'What changed (`event.labels.*`, `event.assignees.*`) only applies to routes that handle work_item.updated or pull_request.updated.';\n }\n if (when && !on.includes('work_item.closed') && namesField(when, ['event.reason'])) {\n return '`event.reason` only applies to routes that handle work_item.closed: no other event carries a reason.';\n }\n return null;\n}\n"],"mappings":";;;;;;;;AASA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AASA,MAAa,uBAAuB;;AAGpC,MAAa,eAAe,CAAC,GAAG,eAAe,oBAAoB;;AAOnE,SAAgB,YAAY,OAA6C;CACvE,OAAO,MAAM,mBAAmB,iBAAiB,iBAAiB;AACpE;;AAUA,SAAgB,aAAa,EAAE,IAAI,8BAA+D;CAChG,MAAM,wBAAQ,IAAI,IAAiB;CACnC,IAAI,GAAG,SAAS,kBAAkB,KAAK,GAAG,SAAA,mBAA6B,GAAG,MAAM,IAAI,OAAO;CAC3F,IAAK,GAAG,SAAS,qBAAqB,KAAK,CAAC,8BAA+B,GAAG,SAAA,m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C,KAAK,MAAM,SAAS,IAAI;EACtB,IAAK,gBAAsC,SAAS,KAAK,GACvD,OAAO,IAAI,MAAM;EAEnB,IAAI,CAAC,aAAa,KAAK,GAAG,OAAO,IAAI,MAAM,qCAAqC,aAAa,KAAK,IAAI,EAAE;CAC1G;CACA,IAAI,QAAQ,GAAG,MAAM,iBAAiB,KAAK,WAAW,MAAM,iBAAiB,GAC3E,OAAO;CAET,IAAI,QAAQ,GAAG,MAAM,iBAAiB,KAAK,WAAW,MAAM,qBAAqB,GAC/E,OAAO;CAET,IAAI,QAAQ,CAAC,GAAG,KAAK,aAAa,KAAK,WAAW,MAAM,kBAAkB,GACxE,OAAO;CAET,IAAI,QAAQ,CAAC,GAAG,SAAS,kBAAkB,KAAK,WAAW,MAAM,CAAC,cAAc,CAAC,GAC/E,OAAO;CAET,OAAO;AACT"}
@@ -13,7 +13,7 @@ import type { ProjectBoardCache } from './project-boards.js';
13
13
  export interface BoardWritesDeps {
14
14
  storage: StoredBoardsStorage;
15
15
  /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */
16
- boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;
16
+ boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'projectSkillNames' | 'seedFor'>;
17
17
  /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */
18
18
  workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;
19
19
  }
@@ -48,10 +48,12 @@ export declare class BoardWrites {
48
48
  refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void;
49
49
  existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord>;
50
50
  /**
51
- * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code
52
- * board's copy is also checked against the code behaviour of its board and phase keys.
51
+ * Validates a definition the way `defineBoard()` does, plus the skills its runners name: the app's,
52
+ * and `projectSkills`, the skills the project it is stored in created. `null` leaves the runners'
53
+ * skills unchecked, for a caller that checks them per project. A code board's copy is also checked
54
+ * against the code behaviour of its board and phase keys.
53
55
  */
54
- validate(input: unknown): StoredBoardInput;
56
+ validate(input: unknown, projectSkills?: ReadonlySet<string> | null): StoredBoardInput;
55
57
  /** Creates a board under a key no code board uses. */
56
58
  create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord>;
57
59
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"board-writes.d.ts","sourceRoot":"","sources":["../../src/boards/board-writes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAG7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,KAAK,EAEV,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EAEpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAI9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAW7D,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,mBAAmB,CAAC;IAC7B,oGAAoG;IACpG,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,UAAU,GAAG,YAAY,GAAG,cAAc,GAAG,YAAY,GAAG,SAAS,CAAC,CAAC;IACvG,gHAAgH;IAChH,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,GAAG,oBAAoB,CAAC,CAAC;CACxE;AAED,6EAA6E;AAC7E,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C;AAED,uFAAuF;AACvF,qBAAa,eAAgB,SAAQ,KAAK;IAGtC,QAAQ,CAAC,MAAM,EAAE,GAA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AAE,gBAAgB,EAAE,MAAM,EAAE,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,WAAW,CAAA;KAAE,GAC9E,OAAO,CAAC,iBAAiB,CAAC,CAsB5B;CA0DF"}
@@ -74,10 +74,12 @@ var BoardWrites = class {
74
74
  return row;
75
75
  }
76
76
  /**
77
- * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code
78
- * board's copy is also checked against the code behaviour of its board and phase keys.
77
+ * Validates a definition the way `defineBoard()` does, plus the skills its runners name: the app's,
78
+ * and `projectSkills`, the skills the project it is stored in created. `null` leaves the runners'
79
+ * skills unchecked, for a caller that checks them per project. A code board's copy is also checked
80
+ * against the code behaviour of its board and phase keys.
79
81
  */
80
- validate(input) {
82
+ validate(input, projectSkills) {
81
83
  const { boards } = this.deps;
82
84
  const parsed = storedBoardInputSchema.safeParse(input);
83
85
  if (!parsed.success) throw new BoardWriteError(422, {
@@ -94,7 +96,8 @@ var BoardWrites = class {
94
96
  });
95
97
  }
96
98
  const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);
97
- const unknown = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills).filter((problem) => problem.includes(UNKNOWN_SKILL));
99
+ if (projectSkills === null) return parsed.data;
100
+ const unknown = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills, void 0, projectSkills).filter((problem) => problem.includes(UNKNOWN_SKILL));
98
101
  if (unknown.length > 0) throw new BoardWriteError(422, {
99
102
  error: "unknown_skill",
100
103
  message: unknown.join(" ")
@@ -105,7 +108,7 @@ var BoardWrites = class {
105
108
  async create(scope, input, writer) {
106
109
  const key = input?.key;
107
110
  if (typeof key === "string") this.refuseCodeBoard(key, "create");
108
- const board = this.validate(input);
111
+ const board = this.validate(input, await this.deps.boards.projectSkillNames(scope));
109
112
  await this.deps.boards.describe(scope);
110
113
  const row = await stored(() => this.deps.storage.create(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null), board.key === "review" ? isUntouchedReviewSeed : void 0));
111
114
  this.deps.boards.invalidate(scope);
@@ -156,7 +159,7 @@ var BoardWrites = class {
156
159
  const input = this.validate({
157
160
  key,
158
161
  ...definition
159
- });
162
+ }, await boards.projectSkillNames(scope));
160
163
  if (row.revision === expectedRevision && sameBoardDefinition(row, input)) return {
161
164
  row,
162
165
  written: false
@@ -1 +1 @@
1
- {"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\n\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n BoardWriteStep,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD, ReviewBoardInUseError } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport { isUntouchedReviewSeed } from './project-boards.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { boardRegistryOf } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */\n workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n if (error instanceof ReviewBoardInUseError) {\n throw new BoardWriteError(409, { error: 'board_in_use', message: error.message, cards: error.cards });\n }\n throw error;\n }\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code\n * board's copy is also checked against the code behaviour of its board and phase keys.\n */\n validate(input: unknown): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills);\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input);\n // Factory stores its boards only into a project that has none, so they go in first.\n await this.deps.boards.describe(scope);\n const row = await stored(() =>\n this.deps.storage.create(\n scope,\n board,\n writer.id,\n this.#takeReviewKey(scope, board.key, null),\n // The row an earlier release seeded for the retired Review board is nobody's board.\n board.key === LEGACY_REVIEW_BOARD ? isUntouchedReviewSeed : undefined,\n ),\n );\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n const inserted = await stored(() =>\n storage.insertIfMissing(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null)),\n );\n if (!inserted) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition });\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n const takeKey = this.#takeReviewKey(scope, key, row);\n // No card is on a seed nobody made into a board: the ones stored there are the retired board's.\n if (!takeKey) await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, {\n expectedRevision,\n actor: writer.id,\n before: takeKey,\n }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n const { intakeRoutes } = await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n for (const route of intakeRoutes) {\n await writer.audit({\n action: 'factory.intake_route.deleted',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'intake_route', id: route.id, name: route.name }],\n metadata: { boardKey: key, cause: 'board_deleted' },\n });\n }\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n // A board the app upserts for every project resets to the app's. Factory's Work resets to the\n // Work the project was stored with: today's for a project Factory created with it, Work with\n // Triage for every other.\n const definition = boards.seedFor(key, row) ?? seed;\n await this.#checkPhasesFree(scope, row, definition.phases);\n const reset = await stored(() => storage.resetTo(scope, key, definition, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /**\n * What a write does first, in its transaction, when it gives the project a board of its own\n * under `review` (none is stored, or only the seed an earlier release left): the cards the\n * retired Review board left stored there get their Work placement, so the new board starts\n * empty. Refused while one of them is still open.\n */\n #takeReviewKey(scope: StoredBoardScope, key: string, row: StoredBoardRecord | null): BoardWriteStep | undefined {\n if (key !== LEGACY_REVIEW_BOARD || (row && !isUntouchedReviewSeed(row))) return undefined;\n return ops => this.deps.workItems.releaseReviewCards(ops, scope, { open: 'refuse' });\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.listShared(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAmDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MAAM,OAAQ,CAAC,CACnG,KAAK,IAAI;AACd;AAEA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;AAGxB,eAAe,OAAU,OAAqC;CAC5D,IAAI;EACF,OAAO,MAAM,MAAM;CACrB,SAAS,OAAO;EACd,IAAI,iBAAiB,kBACnB,MAAM,IAAI,gBAAgB,MAAM,SAAS,oBAAoB,MAAM,KAAK;GACtE,OAAO,MAAM;GACb,SAAS,MAAM;EACjB,CAAC;EAEH,IAAI,iBAAiB,uBACnB,MAAM,IAAI,gBAAgB,KAAK;GAAE,OAAO;GAAgB,SAAS,MAAM;GAAS,OAAO,MAAM;EAAM,CAAC;EAEtG,MAAM;CACR;AACF;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;;;;;CAMrD,gBAAgB,KAAa,QAA4C;EACvE,MAAM,EAAE,WAAW,KAAK;EACxB,MAAM,OAAO,OAAO,aAAa,IAAI,GAAG;EACxC,IAAI,CAAC,MAAM;EACX,MAAM,SAAS,OAAO,QAAQ,GAAG,MAAM,KAAA;EACvC,IAAI,WAAW,UAAU,QAAQ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AO,MAAM;GACjB,QAAQ,iBAAiB;GACzB,kBAAkB,MAAM;GACxB,SAAS,CAAC;IAAE,MAAM;IAAS,IAAI,MAAM;IAAK,MAAM,MAAM;GAAK,CAAC;EAC9D,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\n\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n BoardWriteStep,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD, ReviewBoardInUseError } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport { isUntouchedReviewSeed } from './project-boards.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { boardRegistryOf } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<\n ProjectBoardCache,\n 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'projectSkillNames' | 'seedFor'\n >;\n /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */\n workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n if (error instanceof ReviewBoardInUseError) {\n throw new BoardWriteError(409, { error: 'board_in_use', message: error.message, cards: error.cards });\n }\n throw error;\n }\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name: the app's,\n * and `projectSkills`, the skills the project it is stored in created. `null` leaves the runners'\n * skills unchecked, for a caller that checks them per project. A code board's copy is also checked\n * against the code behaviour of its board and phase keys.\n */\n validate(input: unknown, projectSkills?: ReadonlySet<string> | null): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n if (projectSkills === null) return parsed.data;\n const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills, undefined, projectSkills);\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input, await this.deps.boards.projectSkillNames(scope));\n // Factory stores its boards only into a project that has none, so they go in first.\n await this.deps.boards.describe(scope);\n const row = await stored(() =>\n this.deps.storage.create(\n scope,\n board,\n writer.id,\n this.#takeReviewKey(scope, board.key, null),\n // The row an earlier release seeded for the retired Review board is nobody's board.\n board.key === LEGACY_REVIEW_BOARD ? isUntouchedReviewSeed : undefined,\n ),\n );\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n const inserted = await stored(() =>\n storage.insertIfMissing(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null)),\n );\n if (!inserted) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition }, await boards.projectSkillNames(scope));\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n const takeKey = this.#takeReviewKey(scope, key, row);\n // No card is on a seed nobody made into a board: the ones stored there are the retired board's.\n if (!takeKey) await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, {\n expectedRevision,\n actor: writer.id,\n before: takeKey,\n }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n const { intakeRoutes } = await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n for (const route of intakeRoutes) {\n await writer.audit({\n action: 'factory.intake_route.deleted',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'intake_route', id: route.id, name: route.name }],\n metadata: { boardKey: key, cause: 'board_deleted' },\n });\n }\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n // A board the app upserts for every project resets to the app's. Factory's Work resets to the\n // Work the project was stored with: today's for a project Factory created with it, Work with\n // Triage for every other.\n const definition = boards.seedFor(key, row) ?? seed;\n await this.#checkPhasesFree(scope, row, definition.phases);\n const reset = await stored(() => storage.resetTo(scope, key, definition, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /**\n * What a write does first, in its transaction, when it gives the project a board of its own\n * under `review` (none is stored, or only the seed an earlier release left): the cards the\n * retired Review board left stored there get their Work placement, so the new board starts\n * empty. Refused while one of them is still open.\n */\n #takeReviewKey(scope: StoredBoardScope, key: string, row: StoredBoardRecord | null): BoardWriteStep | undefined {\n if (key !== LEGACY_REVIEW_BOARD || (row && !isUntouchedReviewSeed(row))) return undefined;\n return ops => this.deps.workItems.releaseReviewCards(ops, scope, { open: 'refuse' });\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.listShared(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAsDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MAAM,OAAQ,CAAC,CACnG,KAAK,IAAI;AACd;AAEA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;AAGxB,eAAe,OAAU,OAAqC;CAC5D,IAAI;EACF,OAAO,MAAM,MAAM;CACrB,SAAS,OAAO;EACd,IAAI,iBAAiB,kBACnB,MAAM,IAAI,gBAAgB,MAAM,SAAS,oBAAoB,MAAM,KAAK;GACtE,OAAO,MAAM;GACb,SAAS,MAAM;EACjB,CAAC;EAEH,IAAI,iBAAiB,uBACnB,MAAM,IAAI,gBAAgB,KAAK;GAAE,OAAO;GAAgB,SAAS,MAAM;GAAS,OAAO,MAAM;EAAM,CAAC;EAEtG,MAAM;CACR;AACF;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;;;;;CAMrD,gBAAgB,KAAa,QAA4C;EACvE,MAAM,EAAE,WAAW,KAAK;EACxB,MAAM,OAAO,OAAO,aAAa,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