@mastra/factory 0.29.0-alpha.6 → 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 (149) 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/session-row-view.js +1 -1
  104. package/dist/session/session-row-view.js.map +1 -1
  105. package/dist/session/source-control-tools.d.ts.map +1 -1
  106. package/dist/session/source-control-tools.js +5 -3
  107. package/dist/session/source-control-tools.js.map +1 -1
  108. package/dist/skills/app-skills.d.ts +3 -2
  109. package/dist/skills/app-skills.d.ts.map +1 -1
  110. package/dist/skills/app-skills.js +5 -3
  111. package/dist/skills/app-skills.js.map +1 -1
  112. package/dist/skills/catalog.d.ts +23 -4
  113. package/dist/skills/catalog.d.ts.map +1 -1
  114. package/dist/skills/catalog.js +61 -28
  115. package/dist/skills/catalog.js.map +1 -1
  116. package/dist/storage/domains/audit/actions.d.ts +1 -1
  117. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  118. package/dist/storage/domains/audit/actions.js +6 -1
  119. package/dist/storage/domains/audit/actions.js.map +1 -1
  120. package/dist/storage/domains/boards/base.d.ts +12 -0
  121. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  122. package/dist/storage/domains/boards/base.js +3 -0
  123. package/dist/storage/domains/boards/base.js.map +1 -1
  124. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  125. package/dist/storage/domains/boards/schemas.js +4 -0
  126. package/dist/storage/domains/boards/schemas.js.map +1 -1
  127. package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
  128. package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
  129. package/dist/storage/domains/skill-overrides/base.js +54 -1
  130. package/dist/storage/domains/skill-overrides/base.js.map +1 -1
  131. package/dist/storage/domains/work-items/base.d.ts +2 -0
  132. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  133. package/dist/storage/domains/work-items/base.js +13 -5
  134. package/dist/storage/domains/work-items/base.js.map +1 -1
  135. package/dist/tools/audit-events-tool.d.ts +1 -1
  136. package/dist/tools/read-tools.d.ts.map +1 -1
  137. package/dist/tools/read-tools.js +0 -1
  138. package/dist/tools/read-tools.js.map +1 -1
  139. package/dist/tools/work-item-tools.d.ts.map +1 -1
  140. package/dist/tools/work-item-tools.js +0 -3
  141. package/dist/tools/work-item-tools.js.map +1 -1
  142. package/dist/work-items/create-work-item.d.ts.map +1 -1
  143. package/dist/work-items/create-work-item.js +2 -1
  144. package/dist/work-items/create-work-item.js.map +1 -1
  145. package/dist/workspace.d.ts +5 -1
  146. package/dist/workspace.d.ts.map +1 -1
  147. package/dist/workspace.js +69 -9
  148. package/dist/workspace.js.map +1 -1
  149. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"intake-check.d.ts","sourceRoot":"","sources":["../../src/routes/intake-check.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,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6B,IAAI,EAAE,eAAe,EAAI;IA6EhD,MAAM,CAAC,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,UAAU,qEAe9E;IAEK,IAAI,CAAC,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,QAAQ;;YAO/D,KAAK;YAAc,GAAG;YAAY,IAAI;YAAa,EAAE;;;;;;;;wBAwGjD,MAAM,GAAG,IAAI;gBACrB,MAAM,GAAG,IAAI;mBACV,eAAe;qBAkBT,SAAS;;;;;;wBApBV,MAAM,GAAG,IAAI;gBACrB,MAAM,GAAG,IAAI;mBACV,eAAe;;;;;;;;;;;;;;;;;;;OAnFzB;CA4NF"}
@@ -41,6 +41,7 @@ var IntakeCheck = class {
41
41
  /** The saved rules with each drafted board's rules swapped for its draft, and the draft order if any. */
42
42
  #draft(saved, body, registry) {
43
43
  let routes = [...saved.routes];
44
+ const savedGated = new Set(saved.routes.filter((route) => route.outsiderPullRequestsGated).map((route) => route.id));
44
45
  for (const board of body.boards ?? []) {
45
46
  if (!registry.has(board.boardKey)) throw new IntakeCheckRefusal(422, "intake_board_not_found", `No board "${board.boardKey}" in this project.`);
46
47
  const drafts = board.routes.map((route, index) => ({
@@ -54,7 +55,8 @@ var IntakeCheck = class {
54
55
  joinClosedIssue: route.target.joinClosedIssue ?? false,
55
56
  moveToBoardKey: route.target.moveToBoardKey ?? null
56
57
  },
57
- on: route.on ?? [...DEFAULT_ROUTE_EVENTS]
58
+ on: route.on ?? [...DEFAULT_ROUTE_EVENTS],
59
+ ...route.id !== void 0 && savedGated.has(route.id) && { outsiderPullRequestsGated: true }
58
60
  }));
59
61
  for (const route of drafts) {
60
62
  const problem = intakeTargetProblem(registry, route);
@@ -1 +1 @@
1
- {"version":3,"file":"intake-check.js","names":[],"sources":["../../src/routes/intake-check.ts"],"sourcesContent":["/**\n * The intake dry run and \"Where would this go?\" tester behind the intake routes. Both decide with\n * the intake order evaluator's own code ({@link traceIntakeOrder}), so they answer what filing\n * does under `intake-order`; a project still on `route-list` files differently, and the responses\n * say which evaluator it runs. Both use saved rules or a draft of them, and write nothing: no\n * decision rows, no cards, no audit events, and no provider writes.\n */\n\nimport type { z } from 'zod';\n\nimport { DEFAULT_ROUTE_EVENTS, isUpdateEvent } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport { cardRuleFacts } from '../boards/card-facts.js';\nimport { dryRunIntake, intakeSample } from '../boards/intake-dry-run.js';\nimport { lookupIntakeItem } from '../boards/intake-lookup.js';\nimport type { IntakeItemLookup } from '../boards/intake-lookup.js';\nimport {\n arrivalRuleFacts,\n INTAKE_ORDER_SAMPLE,\n INTAKE_ROUTE_METADATA_KEY,\n intakeTargetProblem,\n planEventMove,\n traceIntakeOrder,\n} from '../boards/intake-routing.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport type { RuleFacts } from '../rules/rule-group.js';\nimport type { FactoryCommitDecision } from '../rules/types.js';\nimport {\n eventRouteIngress,\n FOLDABLE_UPDATE_STATUSES,\n foldsWith,\n foldUpdate,\n updateGroup,\n updateSuperseded,\n} from '../rules/update-fold.js';\nimport type {\n StoredBoardScope,\n StoredBoardsStorage,\n StoredIntakeDecisionRecord,\n StoredIntakeRouteRecord,\n} from '../storage/domains/boards/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { intakeDryRunBodySchema, intakeTestBodySchema } from './contracts.js';\n\ntype DryRunBody = z.infer<typeof intakeDryRunBodySchema>;\ntype TestBody = z.infer<typeof intakeTestBodySchema>;\ntype Draft = Pick<DryRunBody, 'boards' | 'order'>;\ntype DraftRoute = Pick<StoredIntakeRouteRecord, 'id' | 'name' | 'enabled' | 'when' | 'target' | 'on'>;\ntype LinkedDecision = Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n\n/** How many of a card's newest status events the tester replays. */\nexport const RECENT_CARD_EVENTS = 10;\n/** How many of a card's newest decisions the tester reads to find and fold its recent events. */\nexport const CARD_HISTORY = 200;\n\n/** How far back the live counts read the decision log. */\nexport const INTAKE_FILED_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** A request the check refuses: an unknown board in a draft, or a URL it can't test. */\nexport class IntakeCheckRefusal extends Error {\n constructor(\n readonly status: 404 | 422,\n readonly code: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport interface IntakeCheckDeps {\n storage: Pick<\n StoredBoardsStorage,\n 'listIntakeRoutes' | 'readIntakeOrder' | 'listRecentNotRouted' | 'countPlacedByRoute' | 'getIntakeDecision'\n >;\n workItems: Pick<WorkItemsStorage, 'listShared' | 'get' | 'listDeferredDecisions' | 'getTransitionResultByIngress'>;\n /** Providers that can read an item by URL; Linear, Jira and incident.io items are picked from recent ones. */\n lookups?: readonly IntakeItemLookup[];\n now?: () => Date;\n}\n\n/** Whether the request runs anything but the saved rules and order, which needs the right to edit them. */\nexport function isDraft(body: { boards?: unknown; order?: unknown }): boolean {\n return body.boards !== undefined || body.order !== undefined;\n}\n\nexport class IntakeCheck {\n constructor(private readonly deps: IntakeCheckDeps) {}\n\n async #saved(scope: StoredBoardScope, registry: BoardRegistry) {\n const [routes, order] = await Promise.all([\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] }),\n ]);\n return { routes, order: order.boardKeys.filter(key => registry.has(key)) };\n }\n\n /** The saved rules with each drafted board's rules swapped for its draft, and the draft order if any. */\n #draft(saved: { routes: readonly DraftRoute[]; order: string[] }, body: Draft, registry: BoardRegistry) {\n let routes: DraftRoute[] = [...saved.routes];\n for (const board of body.boards ?? []) {\n if (!registry.has(board.boardKey)) {\n throw new IntakeCheckRefusal(422, 'intake_board_not_found', `No board \"${board.boardKey}\" in this project.`);\n }\n const drafts = board.routes.map((route, index) => ({\n id: route.id ?? `draft:${board.boardKey}:${index}`,\n name: route.name,\n enabled: route.enabled,\n when: route.when,\n target: {\n boardKey: board.boardKey,\n phaseKey: route.target.phaseKey ?? null,\n joinClosedIssue: route.target.joinClosedIssue ?? false,\n moveToBoardKey: route.target.moveToBoardKey ?? null,\n },\n on: route.on ?? [...DEFAULT_ROUTE_EVENTS],\n }));\n // Held to the checks saving it would face, so a typo'd phase can't quietly land on the first one.\n for (const route of drafts) {\n const problem = intakeTargetProblem(registry, route);\n if (problem) throw new IntakeCheckRefusal(422, problem.code, problem.message);\n }\n routes = routes.filter(route => route.target.boardKey !== board.boardKey);\n routes.push(...drafts);\n }\n if (new Set(routes.map(route => route.id)).size !== routes.length) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_draft_rule_id_repeated',\n 'Two rules share an id; give each drafted rule its own id, or none.',\n );\n }\n // The same check saving the order faces, so a preview never shows an order that can't be saved.\n if (body.order && (body.order.length !== registry.size || body.order.some(key => !registry.has(key)))) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_order_set_mismatch',\n 'The intake order must list every board of the project exactly once; reload the boards and try again.',\n );\n }\n return { routes, order: body.order ?? saved.order };\n }\n\n async #sample(scope: StoredBoardScope, registry: BoardRegistry) {\n const [cards, notRouted] = await Promise.all([\n this.deps.workItems.listShared(scope),\n this.deps.storage.listRecentNotRouted(scope, INTAKE_ORDER_SAMPLE),\n ]);\n return intakeSample({\n cards,\n notRouted,\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: this.#card(scope),\n });\n }\n\n #card(scope: StoredBoardScope) {\n return (id: string) => this.deps.workItems.get({ orgId: scope.orgId, id });\n }\n\n async dryRun(scope: StoredBoardScope, registry: BoardRegistry, body: DryRunBody) {\n const now = this.deps.now?.() ?? new Date();\n const [saved, items, filed] = await Promise.all([\n this.#saved(scope, registry),\n this.#sample(scope, registry),\n this.deps.storage.countPlacedByRoute(scope, new Date(now.getTime() - INTAKE_FILED_WINDOW_MS)),\n ]);\n const draft = this.#draft(saved, body, registry);\n return dryRunIntake({\n ...draft,\n registry,\n items,\n filed,\n ...(isDraft(body) && { baseline: saved }),\n });\n }\n\n async test(scope: StoredBoardScope, registry: BoardRegistry, body: TestBody) {\n // The draft is checked before the item is read, so a refused draft never costs a provider fetch.\n const { routes, order } = this.#draft(await this.#saved(scope, registry), body, registry);\n const item = await this.#item(scope, registry, body);\n const { resolution, boards } = traceIntakeOrder({ routes, order, facts: item.facts, registry }, { full: true });\n const { card } = item;\n return {\n item: { title: item.title, url: item.url, kind: item.kind, id: item.id },\n current: card\n ? {\n boardKey: boardForWorkItem(card),\n phase: card.stages.length === 1 ? card.stages[0]! : null,\n routeId:\n typeof card.metadata?.[INTAKE_ROUTE_METADATA_KEY] === 'string'\n ? (card.metadata[INTAKE_ROUTE_METADATA_KEY] as string)\n : null,\n }\n : null,\n moves: card ? await this.#moves(scope, registry, routes, card, body.event) : [],\n placement:\n resolution.outcome === 'placed' && resolution.routeId !== null\n ? { boardKey: resolution.board, routeId: resolution.routeId, phase: resolution.phase }\n : null,\n reason: resolution.outcome === 'not_routed' ? resolution.reason : null,\n note:\n item.kind === 'fetched' && item.facts['source.kind'] === 'pull_request'\n ? \"A pull request that closes an issue with a card, or comes from a card's branch, joins that card instead; this test doesn't check for that.\"\n : null,\n boards,\n };\n }\n\n /**\n * The event sent in the request, then the card's newest status events, each replayed through the\n * card-move rules (`planEventMove`, as the dispatcher files them) against the card as it is now.\n */\n async #moves(\n scope: StoredBoardScope,\n registry: BoardRegistry,\n routes: readonly DraftRoute[],\n card: Card,\n tried: BoardEventFacts | undefined,\n ) {\n // Bounded: one decision past the history says whether older ones were left unread.\n const read = await this.deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n newest: CARD_HISTORY + 1,\n workItemId: card.id,\n });\n const truncated = read.length > CARD_HISTORY;\n const records = truncated ? read.slice(1) : read;\n const moveCommitted = async (other: (typeof records)[number]) =>\n Boolean(\n await this.deps.workItems.getTransitionResultByIngress(\n scope.orgId,\n scope.factoryProjectId,\n eventRouteIngress(other.idempotencyKey),\n ),\n );\n // Each update's fold group, built once rather than per record: the first group it folds with.\n const groups: (typeof records)[] = [];\n const groupOf = (decision: Extract<FactoryCommitDecision, { type: 'routeEvent' }>) => {\n let group = groups.find(members => foldsWith(members[0]!.decision, decision));\n if (!group) groups.push((group = updateGroup(records, decision)));\n return group;\n };\n // Which events to show is decided from the records alone, so only those shown are folded:\n // folding reads storage for each earlier update of a burst.\n const shown = records\n .flatMap((record): { record: typeof record; decision: FactoryCommitDecision }[] => {\n // Stored decisions are JSON; these two kinds are the ones that carry a status event.\n const decision = record.decision as unknown as FactoryCommitDecision;\n if (decision.type === 'transition' && decision.event) return [{ record, decision }];\n if (decision.type !== 'routeEvent') return [];\n if (!isUpdateEvent(decision.event.type)) return [{ record, decision }];\n // Updates replay as the dispatcher acts on them: folded into the newest of a burst.\n if (record.status === 'superseded') return [];\n if (FOLDABLE_UPDATE_STATUSES.has(record.status) && updateSuperseded(groupOf(decision), record.id)) {\n return [];\n }\n return [{ record, decision }];\n })\n .slice(-RECENT_CARD_EVENTS);\n const stored = await Promise.all(\n shown.map(\n async ({\n record,\n decision,\n }): Promise<{\n record: typeof record;\n event: BoardEventFacts | undefined;\n unread?: boolean;\n fallback?: { stage: string };\n }> => {\n if (decision.type === 'routeEvent' && isUpdateEvent(decision.event.type)) {\n // Folded as dispatch folded it when it acted: newer updates of its group weren't there yet.\n const group = groupOf(decision);\n const upTo = group.slice(0, group.findIndex(other => other.id === record.id) + 1);\n const fold = await foldUpdate(upTo, record.id, moveCommitted);\n // No earlier update moved the card within what was read, so its burst may reach further back.\n if (truncated && fold.since.length === upTo.length - 1) return { record, event: undefined, unread: true };\n return { record, event: fold.event };\n }\n if (decision.type === 'routeEvent') return { record, event: decision.event };\n if (decision.type === 'transition' && decision.event) {\n return { record, event: decision.event, fallback: { stage: decision.stage } };\n }\n throw new Error(`Decision ${record.id} carries no status event.`);\n },\n ),\n );\n const replays: {\n decisionId: string | null;\n at: string | null;\n event: BoardEventFacts;\n netsOut?: boolean;\n unread?: boolean;\n fallback?: { stage: string };\n }[] = [\n ...(tried ? [{ decisionId: null, at: null, event: tried }] : []),\n ...stored.toReversed().map(({ record, event, unread, fallback }) => ({\n decisionId: record.id,\n at: record.createdAt.toISOString(),\n event: event ?? (record.decision as unknown as { event: BoardEventFacts }).event,\n ...(unread ? { unread } : event === undefined && { netsOut: true }),\n ...(fallback && { fallback }),\n })),\n ];\n return replays.map(({ fallback, netsOut, unread, ...replay }) => {\n if (unread) {\n return {\n ...replay,\n outcome: 'unknown' as const,\n to: null,\n phase: null,\n reason: `Part of the burst it folds is older than the ${CARD_HISTORY} decisions read, so where it lands isn't known.`,\n rules: [],\n };\n }\n // The dispatcher drops an update burst whose labels and assignees end where they started.\n if (netsOut) {\n return {\n ...replay,\n outcome: 'ignored' as const,\n to: null,\n phase: null,\n reason: 'Its labels and assignees end where they started, so it moves nothing.',\n rules: [],\n };\n }\n const plan = planEventMove(\n { routes, event: replay.event, item: card, registry, ...(fallback && { fallback }) },\n { full: true },\n );\n return {\n ...replay,\n outcome: plan.outcome,\n to:\n plan.outcome === 'moves'\n ? { boardKey: plan.move.board, phase: plan.move.phase, routeId: plan.move.routeId }\n : null,\n phase: plan.outcome === 'rule_default' ? plan.phase : null,\n reason: plan.outcome === 'ignored' ? plan.reason : null,\n rules: plan.rules,\n };\n });\n }\n\n /** The item to test: a recent card or Not routed item by id or URL, else one read from its provider. */\n async #item(\n scope: StoredBoardScope,\n registry: BoardRegistry,\n body: TestBody,\n ): Promise<{\n title: string;\n url: string | null;\n kind: 'card' | 'not_routed' | 'fetched';\n id: string | null;\n facts: RuleFacts;\n card?: Card;\n }> {\n // Only a card moves: an event refuses anything else before a provider is asked for it.\n const needsCard = () => {\n if (body.event) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_event_needs_card',\n \"Only a card moves on an event; pick one of the project's cards.\",\n );\n }\n };\n if (body.itemId) {\n const card = await this.deps.workItems.get({ orgId: scope.orgId, id: body.itemId });\n if (card && card.factoryProjectId === scope.factoryProjectId) return fromCard(card);\n const decision = await this.deps.storage.getIntakeDecision(scope, body.itemId);\n if (decision?.arrival) {\n needsCard();\n return this.#notRouted(scope, registry, decision);\n }\n throw new IntakeCheckRefusal(404, 'intake_item_not_found', 'No such item in this project.');\n }\n const url = body.url!;\n const card = (await this.deps.workItems.listShared(scope)).find(\n // The card's own source or any it holds since, such as a pull request linked to an issue card.\n entry => entry.workItem.sources.some(source => source.url !== null && sameUrl(source.url, url)),\n );\n if (card) return fromCard(card);\n needsCard();\n const decision = (await this.deps.storage.listRecentNotRouted(scope, INTAKE_ORDER_SAMPLE)).find(\n entry => entry.arrival && entry.url !== null && sameUrl(entry.url, url),\n );\n const found = await lookupIntakeItem(this.deps.lookups ?? [], scope, url);\n // A Not routed item may have changed since: a label or a reopen takes it in again with the facts it\n // has now, so those answer. Its stored arrival answers only when the provider can't be read.\n if (found.status === 'found')\n return { title: found.title, url: found.url, kind: 'fetched', id: null, facts: found.facts };\n if (decision?.arrival) return this.#notRouted(scope, registry, decision);\n if (found.status === 'not_linked') {\n throw new IntakeCheckRefusal(\n 422,\n 'not_linked',\n \"That item belongs to a repository or team this project isn't linked to.\",\n );\n }\n if (found.status === 'not_found') {\n throw new IntakeCheckRefusal(\n 404,\n 'intake_item_not_found',\n \"The provider has no such item, or it couldn't be read.\",\n );\n }\n throw new IntakeCheckRefusal(\n 422,\n 'intake_url_unsupported',\n 'Paste a GitHub or GitLab issue or pull request URL, or pick a recent item.',\n );\n }\n\n async #notRouted(scope: StoredBoardScope, registry: BoardRegistry, decision: StoredIntakeDecisionRecord) {\n return {\n title: decision.title,\n url: decision.url,\n kind: 'not_routed' as const,\n id: decision.id,\n facts: await arrivalRuleFacts(decision.arrival as unknown as LinkedDecision, {\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: this.#card(scope),\n }),\n };\n }\n}\n\nfunction fromCard(card: Card) {\n return {\n title: card.title,\n url: card.externalSource?.url ?? null,\n kind: 'card' as const,\n id: card.id,\n facts: cardRuleFacts(card),\n card,\n };\n}\n\n// An issue, pull request or merge request URL: host, repository path, kind and number; a tab after it is ignored.\nconst ITEM_URL =\n /^https?:\\/\\/(?:www\\.)?([^/]+)\\/(.+?)\\/(-\\/)?(issues|pull|pulls|merge_requests|work_items)\\/(\\d+)(?:[/?#]|$)/i;\n\n/** Whether two URLs name the same item. GitHub numbers issues and pull requests together; GitLab doesn't. */\nfunction sameUrl(left: string, right: string): boolean {\n const identity = (url: string) => {\n const match = ITEM_URL.exec(url.trim());\n if (!match) return url.trim().replace(/\\/+$/, '').toLowerCase();\n const [, host, path, gitlab, kind, number] = match;\n const family = !gitlab ? 'item' : kind!.toLowerCase() === 'merge_requests' ? 'merge_request' : 'issue';\n return `${host!.toLowerCase()}/${path!.toLowerCase()}/${family}/${number}`;\n };\n return identity(left) === identity(right);\n}\n"],"mappings":";;;;;;;;;AAoDA,MAAa,qBAAqB;;AAElC,MAAa,eAAe;;AAG5B,MAAa,yBAAyB;;AAGtC,IAAa,qBAAb,cAAwC,MAAM;CAEjC;CACA;CAFX,YACE,QACA,MACA,SACA;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EACA,KAAA,OAAA;CAIX;AACF;;AAcA,SAAgB,QAAQ,MAAsD;CAC5E,OAAO,KAAK,WAAW,KAAA,KAAa,KAAK,UAAU,KAAA;AACrD;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;CAErD,MAAM,OAAO,OAAyB,UAAyB;EAC7D,MAAM,CAAC,QAAQ,SAAS,MAAM,QAAQ,IAAI,CACxC,KAAK,KAAK,QAAQ,iBAAiB,KAAK,GACxC,KAAK,KAAK,QAAQ,gBAAgB,OAAO,EAAE,QAAQ,CAAC,GAAG,SAAS,KAAK,CAAC,EAAE,CAAC,CAC3E,CAAC;EACD,OAAO;GAAE;GAAQ,OAAO,MAAM,UAAU,QAAO,QAAO,SAAS,IAAI,GAAG,CAAC;EAAE;CAC3E;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S,MAAY;CAC5B,OAAO;EACL,OAAO,KAAK;EACZ,KAAK,KAAK,gBAAgB,OAAO;EACjC,MAAM;EACN,IAAI,KAAK;EACT,OAAO,cAAc,IAAI;EACzB;CACF;AACF;AAGA,MAAM,WACJ;;AAGF,SAAS,QAAQ,MAAc,OAAwB;CACrD,MAAM,YAAY,QAAgB;EAChC,MAAM,QAAQ,SAAS,KAAK,IAAI,KAAK,CAAC;EACtC,IAAI,CAAC,OAAO,OAAO,IAAI,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;EAC9D,MAAM,GAAG,MAAM,MAAM,QAAQ,MAAM,UAAU;EAC7C,MAAM,SAAS,CAAC,SAAS,SAAS,KAAM,YAAY,MAAM,mBAAmB,kBAAkB;EAC/F,OAAO,GAAG,KAAM,YAAY,EAAE,GAAG,KAAM,YAAY,EAAE,GAAG,OAAO,GAAG;CACpE;CACA,OAAO,SAAS,IAAI,MAAM,SAAS,KAAK;AAC1C"}
1
+ {"version":3,"file":"intake-check.js","names":[],"sources":["../../src/routes/intake-check.ts"],"sourcesContent":["/**\n * The intake dry run and \"Where would this go?\" tester behind the intake routes. Both decide with\n * the intake order evaluator's own code ({@link traceIntakeOrder}), so they answer what filing\n * does under `intake-order`; a project still on `route-list` files differently, and the responses\n * say which evaluator it runs. Both use saved rules or a draft of them, and write nothing: no\n * decision rows, no cards, no audit events, and no provider writes.\n */\n\nimport type { z } from 'zod';\n\nimport { DEFAULT_ROUTE_EVENTS, isUpdateEvent } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport { cardRuleFacts } from '../boards/card-facts.js';\nimport { dryRunIntake, intakeSample } from '../boards/intake-dry-run.js';\nimport { lookupIntakeItem } from '../boards/intake-lookup.js';\nimport type { IntakeItemLookup } from '../boards/intake-lookup.js';\nimport {\n arrivalRuleFacts,\n INTAKE_ORDER_SAMPLE,\n INTAKE_ROUTE_METADATA_KEY,\n intakeTargetProblem,\n planEventMove,\n traceIntakeOrder,\n} from '../boards/intake-routing.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport type { RuleFacts } from '../rules/rule-group.js';\nimport type { FactoryCommitDecision } from '../rules/types.js';\nimport {\n eventRouteIngress,\n FOLDABLE_UPDATE_STATUSES,\n foldsWith,\n foldUpdate,\n updateGroup,\n updateSuperseded,\n} from '../rules/update-fold.js';\nimport type {\n StoredBoardScope,\n StoredBoardsStorage,\n StoredIntakeDecisionRecord,\n StoredIntakeRouteRecord,\n} from '../storage/domains/boards/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { intakeDryRunBodySchema, intakeTestBodySchema } from './contracts.js';\n\ntype DryRunBody = z.infer<typeof intakeDryRunBodySchema>;\ntype TestBody = z.infer<typeof intakeTestBodySchema>;\ntype Draft = Pick<DryRunBody, 'boards' | 'order'>;\ntype DraftRoute = Pick<\n StoredIntakeRouteRecord,\n 'id' | 'name' | 'enabled' | 'when' | 'target' | 'on' | 'outsiderPullRequestsGated'\n>;\ntype LinkedDecision = Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n\n/** How many of a card's newest status events the tester replays. */\nexport const RECENT_CARD_EVENTS = 10;\n/** How many of a card's newest decisions the tester reads to find and fold its recent events. */\nexport const CARD_HISTORY = 200;\n\n/** How far back the live counts read the decision log. */\nexport const INTAKE_FILED_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** A request the check refuses: an unknown board in a draft, or a URL it can't test. */\nexport class IntakeCheckRefusal extends Error {\n constructor(\n readonly status: 404 | 422,\n readonly code: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport interface IntakeCheckDeps {\n storage: Pick<\n StoredBoardsStorage,\n 'listIntakeRoutes' | 'readIntakeOrder' | 'listRecentNotRouted' | 'countPlacedByRoute' | 'getIntakeDecision'\n >;\n workItems: Pick<WorkItemsStorage, 'listShared' | 'get' | 'listDeferredDecisions' | 'getTransitionResultByIngress'>;\n /** Providers that can read an item by URL; Linear, Jira and incident.io items are picked from recent ones. */\n lookups?: readonly IntakeItemLookup[];\n now?: () => Date;\n}\n\n/** Whether the request runs anything but the saved rules and order, which needs the right to edit them. */\nexport function isDraft(body: { boards?: unknown; order?: unknown }): boolean {\n return body.boards !== undefined || body.order !== undefined;\n}\n\nexport class IntakeCheck {\n constructor(private readonly deps: IntakeCheckDeps) {}\n\n async #saved(scope: StoredBoardScope, registry: BoardRegistry) {\n const [routes, order] = await Promise.all([\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] }),\n ]);\n return { routes, order: order.boardKeys.filter(key => registry.has(key)) };\n }\n\n /** The saved rules with each drafted board's rules swapped for its draft, and the draft order if any. */\n #draft(saved: { routes: readonly DraftRoute[]; order: string[] }, body: Draft, registry: BoardRegistry) {\n let routes: DraftRoute[] = [...saved.routes];\n // A draft of a stored gated rule keeps its gate: editing it doesn't widen it, so the preview must not either.\n const savedGated = new Set(saved.routes.filter(route => route.outsiderPullRequestsGated).map(route => route.id));\n for (const board of body.boards ?? []) {\n if (!registry.has(board.boardKey)) {\n throw new IntakeCheckRefusal(422, 'intake_board_not_found', `No board \"${board.boardKey}\" in this project.`);\n }\n const drafts = board.routes.map((route, index) => ({\n id: route.id ?? `draft:${board.boardKey}:${index}`,\n name: route.name,\n enabled: route.enabled,\n when: route.when,\n target: {\n boardKey: board.boardKey,\n phaseKey: route.target.phaseKey ?? null,\n joinClosedIssue: route.target.joinClosedIssue ?? false,\n moveToBoardKey: route.target.moveToBoardKey ?? null,\n },\n on: route.on ?? [...DEFAULT_ROUTE_EVENTS],\n ...(route.id !== undefined && savedGated.has(route.id) && { outsiderPullRequestsGated: true as const }),\n }));\n // Held to the checks saving it would face, so a typo'd phase can't quietly land on the first one.\n for (const route of drafts) {\n const problem = intakeTargetProblem(registry, route);\n if (problem) throw new IntakeCheckRefusal(422, problem.code, problem.message);\n }\n routes = routes.filter(route => route.target.boardKey !== board.boardKey);\n routes.push(...drafts);\n }\n if (new Set(routes.map(route => route.id)).size !== routes.length) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_draft_rule_id_repeated',\n 'Two rules share an id; give each drafted rule its own id, or none.',\n );\n }\n // The same check saving the order faces, so a preview never shows an order that can't be saved.\n if (body.order && (body.order.length !== registry.size || body.order.some(key => !registry.has(key)))) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_order_set_mismatch',\n 'The intake order must list every board of the project exactly once; reload the boards and try again.',\n );\n }\n return { routes, order: body.order ?? saved.order };\n }\n\n async #sample(scope: StoredBoardScope, registry: BoardRegistry) {\n const [cards, notRouted] = await Promise.all([\n this.deps.workItems.listShared(scope),\n this.deps.storage.listRecentNotRouted(scope, INTAKE_ORDER_SAMPLE),\n ]);\n return intakeSample({\n cards,\n notRouted,\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: this.#card(scope),\n });\n }\n\n #card(scope: StoredBoardScope) {\n return (id: string) => this.deps.workItems.get({ orgId: scope.orgId, id });\n }\n\n async dryRun(scope: StoredBoardScope, registry: BoardRegistry, body: DryRunBody) {\n const now = this.deps.now?.() ?? new Date();\n const [saved, items, filed] = await Promise.all([\n this.#saved(scope, registry),\n this.#sample(scope, registry),\n this.deps.storage.countPlacedByRoute(scope, new Date(now.getTime() - INTAKE_FILED_WINDOW_MS)),\n ]);\n const draft = this.#draft(saved, body, registry);\n return dryRunIntake({\n ...draft,\n registry,\n items,\n filed,\n ...(isDraft(body) && { baseline: saved }),\n });\n }\n\n async test(scope: StoredBoardScope, registry: BoardRegistry, body: TestBody) {\n // The draft is checked before the item is read, so a refused draft never costs a provider fetch.\n const { routes, order } = this.#draft(await this.#saved(scope, registry), body, registry);\n const item = await this.#item(scope, registry, body);\n const { resolution, boards } = traceIntakeOrder({ routes, order, facts: item.facts, registry }, { full: true });\n const { card } = item;\n return {\n item: { title: item.title, url: item.url, kind: item.kind, id: item.id },\n current: card\n ? {\n boardKey: boardForWorkItem(card),\n phase: card.stages.length === 1 ? card.stages[0]! : null,\n routeId:\n typeof card.metadata?.[INTAKE_ROUTE_METADATA_KEY] === 'string'\n ? (card.metadata[INTAKE_ROUTE_METADATA_KEY] as string)\n : null,\n }\n : null,\n moves: card ? await this.#moves(scope, registry, routes, card, body.event) : [],\n placement:\n resolution.outcome === 'placed' && resolution.routeId !== null\n ? { boardKey: resolution.board, routeId: resolution.routeId, phase: resolution.phase }\n : null,\n reason: resolution.outcome === 'not_routed' ? resolution.reason : null,\n note:\n item.kind === 'fetched' && item.facts['source.kind'] === 'pull_request'\n ? \"A pull request that closes an issue with a card, or comes from a card's branch, joins that card instead; this test doesn't check for that.\"\n : null,\n boards,\n };\n }\n\n /**\n * The event sent in the request, then the card's newest status events, each replayed through the\n * card-move rules (`planEventMove`, as the dispatcher files them) against the card as it is now.\n */\n async #moves(\n scope: StoredBoardScope,\n registry: BoardRegistry,\n routes: readonly DraftRoute[],\n card: Card,\n tried: BoardEventFacts | undefined,\n ) {\n // Bounded: one decision past the history says whether older ones were left unread.\n const read = await this.deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n newest: CARD_HISTORY + 1,\n workItemId: card.id,\n });\n const truncated = read.length > CARD_HISTORY;\n const records = truncated ? read.slice(1) : read;\n const moveCommitted = async (other: (typeof records)[number]) =>\n Boolean(\n await this.deps.workItems.getTransitionResultByIngress(\n scope.orgId,\n scope.factoryProjectId,\n eventRouteIngress(other.idempotencyKey),\n ),\n );\n // Each update's fold group, built once rather than per record: the first group it folds with.\n const groups: (typeof records)[] = [];\n const groupOf = (decision: Extract<FactoryCommitDecision, { type: 'routeEvent' }>) => {\n let group = groups.find(members => foldsWith(members[0]!.decision, decision));\n if (!group) groups.push((group = updateGroup(records, decision)));\n return group;\n };\n // Which events to show is decided from the records alone, so only those shown are folded:\n // folding reads storage for each earlier update of a burst.\n const shown = records\n .flatMap((record): { record: typeof record; decision: FactoryCommitDecision }[] => {\n // Stored decisions are JSON; these two kinds are the ones that carry a status event.\n const decision = record.decision as unknown as FactoryCommitDecision;\n if (decision.type === 'transition' && decision.event) return [{ record, decision }];\n if (decision.type !== 'routeEvent') return [];\n if (!isUpdateEvent(decision.event.type)) return [{ record, decision }];\n // Updates replay as the dispatcher acts on them: folded into the newest of a burst.\n if (record.status === 'superseded') return [];\n if (FOLDABLE_UPDATE_STATUSES.has(record.status) && updateSuperseded(groupOf(decision), record.id)) {\n return [];\n }\n return [{ record, decision }];\n })\n .slice(-RECENT_CARD_EVENTS);\n const stored = await Promise.all(\n shown.map(\n async ({\n record,\n decision,\n }): Promise<{\n record: typeof record;\n event: BoardEventFacts | undefined;\n unread?: boolean;\n fallback?: { stage: string };\n }> => {\n if (decision.type === 'routeEvent' && isUpdateEvent(decision.event.type)) {\n // Folded as dispatch folded it when it acted: newer updates of its group weren't there yet.\n const group = groupOf(decision);\n const upTo = group.slice(0, group.findIndex(other => other.id === record.id) + 1);\n const fold = await foldUpdate(upTo, record.id, moveCommitted);\n // No earlier update moved the card within what was read, so its burst may reach further back.\n if (truncated && fold.since.length === upTo.length - 1) return { record, event: undefined, unread: true };\n return { record, event: fold.event };\n }\n if (decision.type === 'routeEvent') return { record, event: decision.event };\n if (decision.type === 'transition' && decision.event) {\n return { record, event: decision.event, fallback: { stage: decision.stage } };\n }\n throw new Error(`Decision ${record.id} carries no status event.`);\n },\n ),\n );\n const replays: {\n decisionId: string | null;\n at: string | null;\n event: BoardEventFacts;\n netsOut?: boolean;\n unread?: boolean;\n fallback?: { stage: string };\n }[] = [\n ...(tried ? [{ decisionId: null, at: null, event: tried }] : []),\n ...stored.toReversed().map(({ record, event, unread, fallback }) => ({\n decisionId: record.id,\n at: record.createdAt.toISOString(),\n event: event ?? (record.decision as unknown as { event: BoardEventFacts }).event,\n ...(unread ? { unread } : event === undefined && { netsOut: true }),\n ...(fallback && { fallback }),\n })),\n ];\n return replays.map(({ fallback, netsOut, unread, ...replay }) => {\n if (unread) {\n return {\n ...replay,\n outcome: 'unknown' as const,\n to: null,\n phase: null,\n reason: `Part of the burst it folds is older than the ${CARD_HISTORY} decisions read, so where it lands isn't known.`,\n rules: [],\n };\n }\n // The dispatcher drops an update burst whose labels and assignees end where they started.\n if (netsOut) {\n return {\n ...replay,\n outcome: 'ignored' as const,\n to: null,\n phase: null,\n reason: 'Its labels and assignees end where they started, so it moves nothing.',\n rules: [],\n };\n }\n const plan = planEventMove(\n { routes, event: replay.event, item: card, registry, ...(fallback && { fallback }) },\n { full: true },\n );\n return {\n ...replay,\n outcome: plan.outcome,\n to:\n plan.outcome === 'moves'\n ? { boardKey: plan.move.board, phase: plan.move.phase, routeId: plan.move.routeId }\n : null,\n phase: plan.outcome === 'rule_default' ? plan.phase : null,\n reason: plan.outcome === 'ignored' ? plan.reason : null,\n rules: plan.rules,\n };\n });\n }\n\n /** The item to test: a recent card or Not routed item by id or URL, else one read from its provider. */\n async #item(\n scope: StoredBoardScope,\n registry: BoardRegistry,\n body: TestBody,\n ): Promise<{\n title: string;\n url: string | null;\n kind: 'card' | 'not_routed' | 'fetched';\n id: string | null;\n facts: RuleFacts;\n card?: Card;\n }> {\n // Only a card moves: an event refuses anything else before a provider is asked for it.\n const needsCard = () => {\n if (body.event) {\n throw new IntakeCheckRefusal(\n 422,\n 'intake_event_needs_card',\n \"Only a card moves on an event; pick one of the project's cards.\",\n );\n }\n };\n if (body.itemId) {\n const card = await this.deps.workItems.get({ orgId: scope.orgId, id: body.itemId });\n if (card && card.factoryProjectId === scope.factoryProjectId) return fromCard(card);\n const decision = await this.deps.storage.getIntakeDecision(scope, body.itemId);\n if (decision?.arrival) {\n needsCard();\n return this.#notRouted(scope, registry, decision);\n }\n throw new IntakeCheckRefusal(404, 'intake_item_not_found', 'No such item in this project.');\n }\n const url = body.url!;\n const card = (await this.deps.workItems.listShared(scope)).find(\n // The card's own source or any it holds since, such as a pull request linked to an issue card.\n entry => entry.workItem.sources.some(source => source.url !== null && sameUrl(source.url, url)),\n );\n if (card) return fromCard(card);\n needsCard();\n const decision = (await this.deps.storage.listRecentNotRouted(scope, INTAKE_ORDER_SAMPLE)).find(\n entry => entry.arrival && entry.url !== null && sameUrl(entry.url, url),\n );\n const found = await lookupIntakeItem(this.deps.lookups ?? [], scope, url);\n // A Not routed item may have changed since: a label or a reopen takes it in again with the facts it\n // has now, so those answer. Its stored arrival answers only when the provider can't be read.\n if (found.status === 'found')\n return { title: found.title, url: found.url, kind: 'fetched', id: null, facts: found.facts };\n if (decision?.arrival) return this.#notRouted(scope, registry, decision);\n if (found.status === 'not_linked') {\n throw new IntakeCheckRefusal(\n 422,\n 'not_linked',\n \"That item belongs to a repository or team this project isn't linked to.\",\n );\n }\n if (found.status === 'not_found') {\n throw new IntakeCheckRefusal(\n 404,\n 'intake_item_not_found',\n \"The provider has no such item, or it couldn't be read.\",\n );\n }\n throw new IntakeCheckRefusal(\n 422,\n 'intake_url_unsupported',\n 'Paste a GitHub or GitLab issue or pull request URL, or pick a recent item.',\n );\n }\n\n async #notRouted(scope: StoredBoardScope, registry: BoardRegistry, decision: StoredIntakeDecisionRecord) {\n return {\n title: decision.title,\n url: decision.url,\n kind: 'not_routed' as const,\n id: decision.id,\n facts: await arrivalRuleFacts(decision.arrival as unknown as LinkedDecision, {\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: this.#card(scope),\n }),\n };\n }\n}\n\nfunction fromCard(card: Card) {\n return {\n title: card.title,\n url: card.externalSource?.url ?? null,\n kind: 'card' as const,\n id: card.id,\n facts: cardRuleFacts(card),\n card,\n };\n}\n\n// An issue, pull request or merge request URL: host, repository path, kind and number; a tab after it is ignored.\nconst ITEM_URL =\n /^https?:\\/\\/(?:www\\.)?([^/]+)\\/(.+?)\\/(-\\/)?(issues|pull|pulls|merge_requests|work_items)\\/(\\d+)(?:[/?#]|$)/i;\n\n/** Whether two URLs name the same item. GitHub numbers issues and pull requests together; GitLab doesn't. */\nfunction sameUrl(left: string, right: string): boolean {\n const identity = (url: string) => {\n const match = ITEM_URL.exec(url.trim());\n if (!match) return url.trim().replace(/\\/+$/, '').toLowerCase();\n const [, host, path, gitlab, kind, number] = match;\n const family = !gitlab ? 'item' : kind!.toLowerCase() === 'merge_requests' ? 'merge_request' : 'issue';\n return `${host!.toLowerCase()}/${path!.toLowerCase()}/${family}/${number}`;\n };\n return identity(left) === identity(right);\n}\n"],"mappings":";;;;;;;;;AAuDA,MAAa,qBAAqB;;AAElC,MAAa,eAAe;;AAG5B,MAAa,yBAAyB;;AAGtC,IAAa,qBAAb,cAAwC,MAAM;CAEjC;CACA;CAFX,YACE,QACA,MACA,SACA;EACA,MAAM,OAAO;EAJJ,KAAA,SAAA;EACA,KAAA,OAAA;CAIX;AACF;;AAcA,SAAgB,QAAQ,MAAsD;CAC5E,OAAO,KAAK,WAAW,KAAA,KAAa,KAAK,UAAU,KAAA;AACrD;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,MAAwC;EAAvB,KAAA,OAAA;CAAwB;CAErD,MAAM,OAAO,OAAyB,UAAyB;EAC7D,MAAM,CAAC,QAAQ,SAAS,MAAM,QAAQ,IAAI,CACxC,KAAK,KAAK,QAAQ,iBAAiB,KAAK,GACxC,KAAK,KAAK,QAAQ,gBAAgB,OAAO,EAAE,QAAQ,CAAC,GAAG,SAAS,KAAK,CAAC,EAAE,CAAC,CAC3E,CAAC;EACD,OAAO;GAAE;GAAQ,OAAO,MAAM,UAAU,QAAO,QAAO,SAAS,IAAI,GAAG,CAAC;EAAE;CAC3E;;CAGA,OAAO,OAA2D,MAAa,UAAyB;EACtG,IAAI,SAAuB,CAAC,GAAG,MAAM,MAAM;EAE3C,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,QAAO,UAAS,MAAM,yBAAyB,CAAC,CAAC,KAAI,UAAS,MAAM,EAAE,CAAC;EAC/G,KAAK,MAAM,SAAS,KAAK,UAAU,CAAC,GAAG;GACrC,IAAI,CAAC,SAAS,IAAI,MAAM,QAAQ,GAC9B,MAAM,IAAI,mBAAmB,K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Ac,IAAI;EACzB;CACF;AACF;AAGA,MAAM,WACJ;;AAGF,SAAS,QAAQ,MAAc,OAAwB;CACrD,MAAM,YAAY,QAAgB;EAChC,MAAM,QAAQ,SAAS,KAAK,IAAI,KAAK,CAAC;EACtC,IAAI,CAAC,OAAO,OAAO,IAAI,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE,CAAC,CAAC,YAAY;EAC9D,MAAM,GAAG,MAAM,MAAM,QAAQ,MAAM,UAAU;EAC7C,MAAM,SAAS,CAAC,SAAS,SAAS,KAAM,YAAY,MAAM,mBAAmB,kBAAkB;EAC/F,OAAO,GAAG,KAAM,YAAY,EAAE,GAAG,KAAM,YAAY,EAAE,GAAG,OAAO,GAAG;CACpE;CACA,OAAO,SAAS,IAAI,MAAM,SAAS,KAAK;AAC1C"}
@@ -9,7 +9,6 @@
9
9
  */
10
10
  import type { ApiRoute } from '@mastra/core/server';
11
11
  import type { IntakeItemLookup } from '../boards/intake-lookup.js';
12
- import type { ForcedIntakeEvaluator } from '../boards/intake-routing.js';
13
12
  import type { ProjectBoardCache } from '../boards/project-boards.js';
14
13
  import type { AuditEmitter } from '../storage/domains/audit/domain.js';
15
14
  import type { IntakeEvaluator, StoredBoardsStorage } from '../storage/domains/boards/base.js';
@@ -27,8 +26,6 @@ export interface IntakeRouteRoutesDeps extends RouteDependencies {
27
26
  boards: Pick<ProjectBoardCache, 'describe'>;
28
27
  /** Forces an evaluator on every project; without it each project uses its own setting. */
29
28
  intakeEvaluator?: IntakeEvaluator;
30
- /** What forced `intakeEvaluator`. */
31
- intakeEvaluatorSource?: ForcedIntakeEvaluator['source'];
32
29
  /** Providers the tester can read an unseen item from by URL. */
33
30
  intakeLookups?: readonly IntakeItemLookup[];
34
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"intake-routes.d.ts","sourceRoot":"","sources":["../../src/routes/intake-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,M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B;CACF"}
@@ -167,7 +167,7 @@ var IntakeRouteRoutes = class extends Route {
167
167
  })),
168
168
  origin: stored.origin,
169
169
  evaluator: forced ?? projectEvaluator ?? "route-list",
170
- evaluatorSource: forced ? this.deps.intakeEvaluatorSource ?? "option" : projectEvaluator ? "project" : "legacy",
170
+ evaluatorSource: forced ? "env" : projectEvaluator ? "project" : "legacy",
171
171
  projectEvaluator,
172
172
  comparison: compareIntakeOrder({
173
173
  routes,
@@ -1 +1 @@
1
- {"version":3,"file":"intake-routes.js","names":[],"sources":["../../src/routes/intake-routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for managing a project's intake routes: the ordered rules that place new\n * cards on a board and phase when they arrive.\n *\n * Reads need a signed-in user of the project's organization; writes need an organization admin in\n * tenant mode. A route's target must be an installed board and a phase new cards can reach when it\n * is written; a target that\n * stops existing later is reported in `problems` and skipped when cards arrive.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport type { z } from 'zod';\nimport { DEFAULT_ROUTE_EVENTS } from '../boards/board-events.js';\n\nimport type { RouteEvent } from '../boards/board-events.js';\nimport type { IntakeItemLookup } from '../boards/intake-lookup.js';\nimport {\n arrivalRuleFacts,\n compareIntakeOrder,\n intakeTargetProblem,\n projectIntakeEvaluator,\n resolveIntake,\n ROUTE_AGAIN_KEY_PREFIX,\n} from '../boards/intake-routing.js';\nimport type { ForcedIntakeEvaluator } from '../boards/intake-routing.js';\nimport type { ProjectBoardCache } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { applyReroute, planReroute, summarizeReroute } from '../boards/reroute.js';\nimport type { FactoryCommitDecision } from '../rules/types.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n IntakeEvaluator,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredIntakeDecisionRecord,\n StoredIntakeRouteRecord,\n} from '../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport { IntakeCheck, IntakeCheckRefusal, isDraft } from './intake-check.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface IntakeRouteRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n projects: FactoryProjectsStorage;\n storage: StoredBoardsStorage;\n /** Cards an intake route change may move to another board. */\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'update'\n | 'supersedeDecisionsForWorkItem'\n | 'get'\n | 'commitRuleEvaluation'\n | 'listDeferredDecisions'\n | 'getTransitionResultByIngress'\n >;\n /** The project's installed boards, to check route targets against. */\n boards: Pick<ProjectBoardCache, 'describe'>;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n /** What forced `intakeEvaluator`. */\n intakeEvaluatorSource?: ForcedIntakeEvaluator['source'];\n /** Providers the tester can read an unseen item from by URL. */\n intakeLookups?: readonly IntakeItemLookup[];\n}\n\ntype LinkedDecision = Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n\nfunction presentDecision(decision: StoredIntakeDecisionRecord) {\n const { boardKey, routeId, reason, sourceKey, title, url, decidedAt, id, outcome, evaluator } = decision;\n return { id, outcome, evaluator, boardKey, routeId, reason, sourceKey, title, url, decidedAt };\n}\n\n/** How far back the Rules page counts a card-move rule's skips. */\nconst SKIPPED_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype Resolved = StoredBoardScope & { userId: string };\n\n/** A response the handler returns as is: a refusal or an error. */\nclass Refusal {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422,\n readonly body: Record<string, unknown>,\n ) {}\n}\n\nfunction 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\nfunction present(route: StoredIntakeRouteRecord, registry: BoardRegistry) {\n const { orgId: _orgId, factoryProjectId: _project, ...fields } = route;\n const problem = intakeTargetProblem(registry, route);\n return { ...fields, problems: problem ? [problem.message] : [] };\n}\n\nexport class IntakeRouteRoutes extends Route<IntakeRouteRoutesDeps> {\n async #resolve(c: Context): Promise<Resolved> {\n const { auth, projects } = this.deps;\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) throw new Refusal(401, { error: 'unauthorized' });\n if (!tenant.orgId) {\n throw new Refusal(403, { error: 'organization_required', message: 'Intake routes belong to an organization.' });\n }\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteList.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsed.success) throw new Refusal(404, { error: 'Project not found' });\n await projects.ensureReady();\n if (!(await projects.get({ orgId: tenant.orgId, id: parsed.data.id }))) {\n throw new Refusal(404, { error: 'Project not found' });\n }\n return { orgId: tenant.orgId, userId: tenant.userId, factoryProjectId: parsed.data.id };\n }\n\n async #requireAdmin(c: Context, scope: Resolved): Promise<void> {\n const { auth } = this.deps;\n if (auth.enabled() && !(await auth.isOrganizationAdmin(c, scope.orgId))) {\n throw new Refusal(403, {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to change intake routes.',\n });\n }\n }\n\n async #body<T>(c: Context, schema: z.ZodType<T>): Promise<T> {\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n throw new Refusal(400, { error: 'invalid_request', message: 'Invalid JSON body.' });\n }\n const parsed = schema.safeParse(body);\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_intake_route', message: issueMessage(parsed.error.issues) });\n }\n return parsed.data;\n }\n\n #routeId(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteGet.pathSchema.safeParse({\n id: c.req.param('id'),\n routeId: c.req.param('routeId'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'intake_route_not_found' });\n return parsed.data.routeId;\n }\n\n async #registry(scope: Resolved): Promise<BoardRegistry> {\n return (await this.deps.boards.describe(scope)).registry;\n }\n\n /** Refuses a target that isn't an installed board and phase, or, for a route placing new cards, one they can't land in. */\n async #checkTarget(\n scope: Resolved,\n route: {\n target: { boardKey: string; phaseKey?: string | null; joinClosedIssue?: boolean; moveToBoardKey?: string | null };\n on: readonly RouteEvent[];\n pullRequestOpenedMovesOnly?: boolean;\n },\n ) {\n const problem = intakeTargetProblem(await this.#registry(scope), route);\n if (problem) throw new Refusal(422, { error: problem.code, message: problem.message });\n }\n\n #evaluator(scope: Resolved): Promise<IntakeEvaluator> {\n return projectIntakeEvaluator(this.deps.intakeEvaluator, this.deps.storage, scope);\n }\n\n async #order(scope: Resolved, registry: BoardRegistry, evaluator: IntakeEvaluator): Promise<string[]> {\n if (evaluator !== 'intake-order') return [];\n const order = await this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] });\n return order.boardKeys.filter(key => registry.has(key));\n }\n\n /** Pull requests link to the card of the issue they close on their own; a route can't join them any more. */\n #refuseJoin(target: { joinClosedIssue?: boolean } | undefined, current?: { joinClosedIssue: boolean }) {\n if (target?.joinClosedIssue === true && current?.joinClosedIssue !== true) {\n throw new Refusal(422, {\n error: 'join_retired',\n message:\n 'Pull requests link to the card of the issue they close on their own. Use a card-move rule on pull_request.opened to move that card.',\n });\n }\n }\n\n async #planReroute(scope: Resolved) {\n const [registry, routes, items] = await Promise.all([\n this.#registry(scope),\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.workItems.listShared(scope),\n ]);\n const evaluator = await this.#evaluator(scope);\n return planReroute(routes, items, registry, { evaluator, order: await this.#order(scope, registry, evaluator) });\n }\n\n async #canEdit(c: Context, scope: Resolved): Promise<boolean> {\n const { auth } = this.deps;\n return !auth.enabled() || (await auth.isOrganizationAdmin(c, scope.orgId));\n }\n\n async #list(c: Context, scope: Resolved, routes?: StoredIntakeRouteRecord[]) {\n const registry = await this.#registry(scope);\n routes ??= await this.deps.storage.listIntakeRoutes(scope);\n return c.json({\n intakeRoutes: routes.map(route => present(route, registry)),\n canEdit: await this.#canEdit(c, scope),\n });\n }\n\n /** The project's boards in intake order: the stored order, with any board it lacks slotted in as a new one is. */\n async #intakeOrder(c: Context, scope: Resolved) {\n const registry = await this.#registry(scope);\n const [stored, routes, cards, projectEvaluator] = await Promise.all([\n this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] }),\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.workItems.listShared(scope),\n this.deps.storage.intakeEvaluator(scope),\n ]);\n const forced = this.deps.intakeEvaluator;\n const listed = stored.boardKeys.filter(key => registry.has(key));\n const order = [...listed, ...[...registry.keys()].filter(key => !listed.includes(key))];\n return c.json({\n boards: order.map(boardKey => ({ boardKey, name: registry.get(boardKey)!.name })),\n origin: stored.origin,\n evaluator: forced ?? projectEvaluator ?? 'route-list',\n evaluatorSource: forced ? (this.deps.intakeEvaluatorSource ?? 'option') : projectEvaluator ? 'project' : 'legacy',\n projectEvaluator,\n // Worked out on every read, so it always describes the order in force and today's rules.\n comparison: compareIntakeOrder({ routes, order, registry, cards }),\n canEdit: await this.#canEdit(c, scope),\n });\n }\n\n #decisionId(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteAgain.pathSchema.safeParse({\n id: c.req.param('id'),\n decisionId: c.req.param('decisionId'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'intake_decision_not_found' });\n return parsed.data.decisionId;\n }\n\n /**\n * Runs intake again for an item no board took. Refuses while no board's rules take it; otherwise\n * commits the item's arrival afresh, so the dispatcher files it as a new arrival would be.\n */\n async #routeAgain(c: Context, scope: Resolved) {\n const { storage, workItems } = this.deps;\n const decision = await storage.getIntakeDecision(scope, this.#decisionId(c));\n if (!decision || decision.outcome !== 'not_routed' || !decision.arrival) {\n throw new Refusal(404, { error: 'intake_decision_not_found' });\n }\n if (decision.resolvedAt) {\n throw new Refusal(409, { error: 'intake_decision_resolved', message: 'This item has been filed since.' });\n }\n const arrival = decision.arrival as unknown as LinkedDecision;\n const [registry, routes] = await Promise.all([this.#registry(scope), storage.listIntakeRoutes(scope)]);\n // Only intake order leaves an item Not routed, so it decides again whatever this replica runs.\n const resolution = resolveIntake({\n evaluator: 'intake-order',\n routes,\n order: await this.#order(scope, registry, 'intake-order'),\n facts: await arrivalRuleFacts(arrival, {\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: id => workItems.get({ orgId: scope.orgId, id }),\n }),\n registry,\n });\n if (resolution.outcome === 'not_routed') {\n throw new Refusal(422, { error: 'intake_not_routed', message: resolution.reason });\n }\n if (resolution.routeId === null) {\n throw new Refusal(422, { error: 'intake_not_routed', message: \"No board's intake rules match it.\" });\n }\n const attempt = `${ROUTE_AGAIN_KEY_PREFIX}${decision.id}:${globalThis.crypto.randomUUID()}`;\n await workItems.commitRuleEvaluation({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n workItemId: null,\n ingress: { identity: attempt },\n expectedRevision: null,\n actor: { type: 'system', id: 'factory-intake-route-again' },\n outcome: { status: 'accepted' },\n decisions: [{ ...arrival, idempotencyKey: attempt }],\n causalChain: [],\n now: new Date(),\n });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake.routed_again',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'intake_decision', id: decision.id, name: decision.title }],\n metadata: { sourceKey: decision.sourceKey, boardKey: resolution.board, routeId: resolution.routeId },\n },\n });\n return c.json(\n { status: 'queued', boardKey: resolution.board, phaseKey: resolution.phase, routeId: resolution.routeId },\n 202,\n );\n }\n\n async #respond(c: Context, scope: Resolved, route: StoredIntakeRouteRecord, status: 200 | 201 = 200) {\n return c.json({ intakeRoute: present(route, await this.#registry(scope)) }, status);\n }\n\n async #audit(\n c: Context,\n scope: Resolved,\n action: 'created' | 'updated' | 'deleted' | 'reordered',\n targets: { id: string; name: string }[],\n ) {\n await this.deps.audit.emit({\n context: c,\n input: {\n action: `factory.intake_route.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: targets.map(route => ({ type: 'intake_route', id: route.id, name: route.name })),\n },\n });\n }\n\n #route(\n contract: { path: string; method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' },\n handle: (c: Context) => Promise<Response>,\n ): ApiRoute {\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n try {\n return await handle(context);\n } catch (error) {\n if (error instanceof Refusal) return context.json(error.body, error.status);\n if (error instanceof IntakeCheckRefusal) {\n return context.json({ error: error.code, message: error.message }, error.status);\n }\n if (error instanceof StoredBoardError) {\n return context.json(\n { error: error.code, message: error.message },\n error.code === 'intake_route_not_found' || error.code === 'intake_decision_not_found'\n ? 404\n : error.code === 'invalid_intake_route' ||\n error.code === 'intake_route_limit' ||\n error.code === 'invalid_intake_cursor'\n ? 422\n : 409,\n );\n }\n throw error;\n }\n },\n });\n }\n\n /** Members read the saved rules; running a draft of them needs the right to edit them. */\n async #check<T extends { boards?: unknown; order?: unknown }>(c: Context, schema: z.ZodType<T>) {\n const scope = await this.#resolve(c);\n const body = await this.#body(c, schema);\n if (isDraft(body)) await this.#requireAdmin(c, scope);\n const check = new IntakeCheck({\n storage: this.deps.storage,\n workItems: this.deps.workItems,\n ...(this.deps.intakeLookups && { lookups: this.deps.intakeLookups }),\n });\n return { scope, body, check, registry: await this.#registry(scope) };\n }\n\n routes(): ApiRoute[] {\n const { storage } = this.deps;\n const contracts = FACTORY_ROUTE_CONTRACTS;\n return [\n this.#route(contracts.intakeDryRun, async c => {\n const { scope, body, check, registry } = await this.#check(c, contracts.intakeDryRun.bodySchema);\n return c.json({\n ...(await check.dryRun(scope, registry, body)),\n evaluator: await this.#evaluator(scope),\n canEdit: await this.#canEdit(c, scope),\n });\n }),\n\n this.#route(contracts.intakeTest, async c => {\n const { scope, body, check, registry } = await this.#check(c, contracts.intakeTest.bodySchema);\n return c.json({ ...(await check.test(scope, registry, body)), evaluator: await this.#evaluator(scope) });\n }),\n\n this.#route(contracts.intakeRouteList, async c => {\n const scope = await this.#resolve(c);\n const query = contracts.intakeRouteList.querySchema.safeParse({ boardKey: c.req.query('boardKey') });\n if (!query.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(query.error.issues) });\n }\n const { boardKey } = query.data;\n return this.#list(\n c,\n scope,\n boardKey === undefined ? undefined : await storage.listIntakeRoutes(scope, { boardKey }),\n );\n }),\n\n this.#route(contracts.intakeOrderGet, async c => this.#intakeOrder(c, await this.#resolve(c))),\n\n this.#route(contracts.intakeOrderUpdate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const { boardKeys, evaluator } = await this.#body(c, contracts.intakeOrderUpdate.bodySchema);\n const registry = await this.#registry(scope);\n const targets = [{ type: 'factory_project', id: scope.factoryProjectId }];\n if (boardKeys) {\n const before = await storage.readIntakeOrder(scope, { boards: [...registry.keys()] });\n await storage.setIntakeOrder(scope, boardKeys, { boards: [...registry.keys()] });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_order.updated',\n factoryProjectId: scope.factoryProjectId,\n targets,\n metadata: { before: before.boardKeys, after: boardKeys },\n },\n });\n }\n if (evaluator) {\n const before = await storage.setIntakeEvaluator(scope, evaluator);\n if (before !== evaluator) {\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_order.evaluator_updated',\n factoryProjectId: scope.factoryProjectId,\n targets,\n metadata: { before, after: evaluator },\n },\n });\n }\n }\n return this.#intakeOrder(c, scope);\n }),\n\n this.#route(contracts.intakeNotRoutedList, async c => {\n const scope = await this.#resolve(c);\n const query = contracts.intakeNotRoutedList.querySchema.safeParse({\n limit: c.req.query('limit'),\n cursor: c.req.query('cursor'),\n });\n if (!query.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(query.error.issues) });\n }\n const page = await storage.listNotRouted(scope, query.data);\n return c.json({\n notRouted: page.notRouted.map(presentDecision),\n nextCursor: page.nextCursor,\n canEdit: await this.#canEdit(c, scope),\n });\n }),\n\n this.#route(contracts.intakeSkippedList, async c => {\n const scope = await this.#resolve(c);\n const summary = await storage.summarizeSkippedByRoute(scope, new Date(Date.now() - SKIPPED_WINDOW_MS));\n return c.json({\n skipped: Object.entries(summary).map(([routeId, { count, latest }]) => ({\n routeId,\n count,\n latest: presentDecision(latest),\n })),\n });\n }),\n\n this.#route(contracts.intakeRouteAgain, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n return this.#routeAgain(c, scope);\n }),\n\n this.#route(contracts.intakeRouteReroutePreview, async c => {\n const scope = await this.#resolve(c);\n const moves = await this.#planReroute(scope);\n return c.json({ total: moves.length, moves: summarizeReroute(moves) });\n }),\n\n this.#route(contracts.intakeRouteRerouteApply, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const moves = await this.#planReroute(scope);\n const result = await applyReroute({\n moves,\n workItems: this.deps.workItems,\n registry: await this.#registry(scope),\n userId: scope.userId,\n });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_route.rerouted',\n factoryProjectId: scope.factoryProjectId,\n targets: [...new Set(moves.map(move => move.routeId))].map(id => ({ type: 'intake_route', id })),\n metadata: { ...result, moves: summarizeReroute(moves) },\n },\n });\n return c.json(result);\n }),\n\n this.#route(contracts.intakeRouteReorder, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const { ids, boardKey } = await this.#body(c, contracts.intakeRouteReorder.bodySchema);\n const routes = await storage.reorderIntakeRoutes(\n scope,\n ids,\n scope.userId,\n boardKey === undefined ? {} : { boardKey },\n );\n await this.#audit(c, scope, 'reordered', routes);\n return this.#list(c, scope, routes);\n }),\n\n this.#route(contracts.intakeRouteGet, async c => {\n const scope = await this.#resolve(c);\n const route = await storage.getIntakeRoute(scope, this.#routeId(c));\n if (!route) throw new Refusal(404, { error: 'intake_route_not_found' });\n return this.#respond(c, scope, route);\n }),\n\n this.#route(contracts.intakeRouteCreate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const input = await this.#body(c, contracts.intakeRouteCreate.bodySchema);\n this.#refuseJoin(input.target);\n await this.#checkTarget(scope, {\n target: input.target,\n on: input.on ?? DEFAULT_ROUTE_EVENTS,\n pullRequestOpenedMovesOnly: input.pullRequestOpenedMovesOnly,\n });\n const route = await storage.createIntakeRoute(scope, input, scope.userId);\n await this.#audit(c, scope, 'created', [route]);\n return this.#respond(c, scope, route, 201);\n }),\n\n this.#route(contracts.intakeRouteUpdate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const id = this.#routeId(c);\n const { expectedRevision, ...patch } = await this.#body(c, contracts.intakeRouteUpdate.bodySchema);\n if (patch.target || patch.on) {\n // Narrowing or widening `on` changes which targets are allowed, so check the route as it will be.\n const current = await storage.getIntakeRoute(scope, id);\n if (!current) throw new Refusal(404, { error: 'intake_route_not_found' });\n this.#refuseJoin(patch.target, current.target);\n // Under intake order a rule belongs to its board: it moves with it, never to another.\n if (\n (await this.#evaluator(scope)) === 'intake-order' &&\n patch.target &&\n patch.target.boardKey !== current.target.boardKey\n ) {\n throw new Refusal(422, {\n error: 'intake_route_board_fixed',\n message: `This rule belongs to board \"${current.target.boardKey}\"; add a rule on the other board instead.`,\n });\n }\n // A 0.28 `pull_request.opened` route stays a card move through every edit, `on` included.\n await this.#checkTarget(scope, {\n target: patch.target ?? current.target,\n on: patch.on ?? current.on,\n pullRequestOpenedMovesOnly: current.pullRequestOpenedMovesOnly,\n });\n }\n const route = await storage.updateIntakeRoute(scope, id, patch, { expectedRevision, actor: scope.userId });\n await this.#audit(c, scope, 'updated', [route]);\n return this.#respond(c, scope, route);\n }),\n\n this.#route(contracts.intakeRouteDelete, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const id = this.#routeId(c);\n const parsed = contracts.intakeRouteDelete.querySchema.safeParse({\n expectedRevision: c.req.query('expectedRevision'),\n });\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n const route = await storage.getIntakeRoute(scope, id);\n if (!route) throw new Refusal(404, { error: 'intake_route_not_found' });\n await storage.deleteIntakeRoute(scope, id, { expectedRevision: parsed.data.expectedRevision });\n await this.#audit(c, scope, 'deleted', [route]);\n return c.body(null, 204);\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;AA0EA,SAAS,gBAAgB,UAAsC;CAC7D,MAAM,EAAE,UAAU,SAAS,QAAQ,WAAW,OAAO,KAAK,WAAW,IAAI,SAAS,cAAc;CAChG,OAAO;EAAE;EAAI;EAAS;EAAW;EAAU;EAAS;EAAQ;EAAW;EAAO;EAAK;CAAU;AAC/F;;AAGA,MAAM,oBAAoB;;AAK1B,IAAM,UAAN,MAAc;CAED;CACA;CAFX,YACE,QACA,MACA;EAFS,KAAA,SAAA;EACA,KAAA,OAAA;CACR;AACL;AAEA,SAAS,aAAa,QAA6C;CACjE,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,SAAS,QAAQ,OAAgC,UAAyB;CACxE,MAAM,EAAE,OAAO,QAAQ,kBAAkB,UAAU,GAAG,WAAW;CACjE,MAAM,UAAU,oBAAoB,UAAU,KAAK;CACnD,OAAO;EAAE,GAAG;EAAQ,UAAU,UAAU,CAAC,QAAQ,OAAO,IAAI,CAAC;CAAE;AACjE;AAEA,IAAa,oBAAb,cAAuC,MAA6B;CAClE,MAAM,SAAS,GAA+B;EAC5C,MAAM,EAAE,MAAM,aAAa,KAAK;EAChC,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,eAA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MAAM,KAAK,SAAS,CAAC;IACnC,MAAM,KAAK,cAAc,GAAG,KAAK;IACjC,MAAM,KAAK,KAAK,SAAS,CAAC;IAC1B,MAAM,SAAS,UAAU,kBAAkB,YAAY,UAAU,EAC/D,kBAAkB,EAAE,IAAI,MAAM,kBAAkB,EAClD,CAAC;IACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,QAAQ,KAAK;KAAE,OAAO;KAAmB,SAAS,aAAa,OAAO,MAAM,MAAM;IAAE,CAAC;IAEjG,MAAM,QAAQ,MAAM,QAAQ,eAAe,OAAO,EAAE;IACpD,IAAI,CAAC,OAAO,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,yBAAyB,CAAC;IACtE,MAAM,QAAQ,kBAAkB,OAAO,IAAI,EAAE,kBAAkB,OAAO,KAAK,iBAAiB,CAAC;IAC7F,MAAM,KAAK,OAAO,GAAG,OAAO,WAAW,CAAC,KAAK,CAAC;IAC9C,OAAO,EAAE,KAAK,MAAM,GAAG;GACzB,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"intake-routes.js","names":[],"sources":["../../src/routes/intake-routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for managing a project's intake routes: the ordered rules that place new\n * cards on a board and phase when they arrive.\n *\n * Reads need a signed-in user of the project's organization; writes need an organization admin in\n * tenant mode. A route's target must be an installed board and a phase new cards can reach when it\n * is written; a target that\n * stops existing later is reported in `problems` and skipped when cards arrive.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport type { z } from 'zod';\nimport { DEFAULT_ROUTE_EVENTS } from '../boards/board-events.js';\n\nimport type { RouteEvent } from '../boards/board-events.js';\nimport type { IntakeItemLookup } from '../boards/intake-lookup.js';\nimport {\n arrivalRuleFacts,\n compareIntakeOrder,\n intakeTargetProblem,\n projectIntakeEvaluator,\n resolveIntake,\n ROUTE_AGAIN_KEY_PREFIX,\n} from '../boards/intake-routing.js';\nimport type { ProjectBoardCache } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { applyReroute, planReroute, summarizeReroute } from '../boards/reroute.js';\nimport type { FactoryCommitDecision } from '../rules/types.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n IntakeEvaluator,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredIntakeDecisionRecord,\n StoredIntakeRouteRecord,\n} from '../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport { IntakeCheck, IntakeCheckRefusal, isDraft } from './intake-check.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface IntakeRouteRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n projects: FactoryProjectsStorage;\n storage: StoredBoardsStorage;\n /** Cards an intake route change may move to another board. */\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'update'\n | 'supersedeDecisionsForWorkItem'\n | 'get'\n | 'commitRuleEvaluation'\n | 'listDeferredDecisions'\n | 'getTransitionResultByIngress'\n >;\n /** The project's installed boards, to check route targets against. */\n boards: Pick<ProjectBoardCache, 'describe'>;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n /** Providers the tester can read an unseen item from by URL. */\n intakeLookups?: readonly IntakeItemLookup[];\n}\n\ntype LinkedDecision = Extract<FactoryCommitDecision, { type: 'upsertLinkedWorkItem' }>;\n\nfunction presentDecision(decision: StoredIntakeDecisionRecord) {\n const { boardKey, routeId, reason, sourceKey, title, url, decidedAt, id, outcome, evaluator } = decision;\n return { id, outcome, evaluator, boardKey, routeId, reason, sourceKey, title, url, decidedAt };\n}\n\n/** How far back the Rules page counts a card-move rule's skips. */\nconst SKIPPED_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype Resolved = StoredBoardScope & { userId: string };\n\n/** A response the handler returns as is: a refusal or an error. */\nclass Refusal {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422,\n readonly body: Record<string, unknown>,\n ) {}\n}\n\nfunction 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\nfunction present(route: StoredIntakeRouteRecord, registry: BoardRegistry) {\n const { orgId: _orgId, factoryProjectId: _project, ...fields } = route;\n const problem = intakeTargetProblem(registry, route);\n return { ...fields, problems: problem ? [problem.message] : [] };\n}\n\nexport class IntakeRouteRoutes extends Route<IntakeRouteRoutesDeps> {\n async #resolve(c: Context): Promise<Resolved> {\n const { auth, projects } = this.deps;\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) throw new Refusal(401, { error: 'unauthorized' });\n if (!tenant.orgId) {\n throw new Refusal(403, { error: 'organization_required', message: 'Intake routes belong to an organization.' });\n }\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteList.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsed.success) throw new Refusal(404, { error: 'Project not found' });\n await projects.ensureReady();\n if (!(await projects.get({ orgId: tenant.orgId, id: parsed.data.id }))) {\n throw new Refusal(404, { error: 'Project not found' });\n }\n return { orgId: tenant.orgId, userId: tenant.userId, factoryProjectId: parsed.data.id };\n }\n\n async #requireAdmin(c: Context, scope: Resolved): Promise<void> {\n const { auth } = this.deps;\n if (auth.enabled() && !(await auth.isOrganizationAdmin(c, scope.orgId))) {\n throw new Refusal(403, {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to change intake routes.',\n });\n }\n }\n\n async #body<T>(c: Context, schema: z.ZodType<T>): Promise<T> {\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n throw new Refusal(400, { error: 'invalid_request', message: 'Invalid JSON body.' });\n }\n const parsed = schema.safeParse(body);\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_intake_route', message: issueMessage(parsed.error.issues) });\n }\n return parsed.data;\n }\n\n #routeId(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteGet.pathSchema.safeParse({\n id: c.req.param('id'),\n routeId: c.req.param('routeId'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'intake_route_not_found' });\n return parsed.data.routeId;\n }\n\n async #registry(scope: Resolved): Promise<BoardRegistry> {\n return (await this.deps.boards.describe(scope)).registry;\n }\n\n /** Refuses a target that isn't an installed board and phase, or, for a route placing new cards, one they can't land in. */\n async #checkTarget(\n scope: Resolved,\n route: {\n target: { boardKey: string; phaseKey?: string | null; joinClosedIssue?: boolean; moveToBoardKey?: string | null };\n on: readonly RouteEvent[];\n pullRequestOpenedMovesOnly?: boolean;\n },\n ) {\n const problem = intakeTargetProblem(await this.#registry(scope), route);\n if (problem) throw new Refusal(422, { error: problem.code, message: problem.message });\n }\n\n #evaluator(scope: Resolved): Promise<IntakeEvaluator> {\n return projectIntakeEvaluator(this.deps.intakeEvaluator, this.deps.storage, scope);\n }\n\n async #order(scope: Resolved, registry: BoardRegistry, evaluator: IntakeEvaluator): Promise<string[]> {\n if (evaluator !== 'intake-order') return [];\n const order = await this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] });\n return order.boardKeys.filter(key => registry.has(key));\n }\n\n /** Pull requests link to the card of the issue they close on their own; a route can't join them any more. */\n #refuseJoin(target: { joinClosedIssue?: boolean } | undefined, current?: { joinClosedIssue: boolean }) {\n if (target?.joinClosedIssue === true && current?.joinClosedIssue !== true) {\n throw new Refusal(422, {\n error: 'join_retired',\n message:\n 'Pull requests link to the card of the issue they close on their own. Use a card-move rule on pull_request.opened to move that card.',\n });\n }\n }\n\n async #planReroute(scope: Resolved) {\n const [registry, routes, items] = await Promise.all([\n this.#registry(scope),\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.workItems.listShared(scope),\n ]);\n const evaluator = await this.#evaluator(scope);\n return planReroute(routes, items, registry, { evaluator, order: await this.#order(scope, registry, evaluator) });\n }\n\n async #canEdit(c: Context, scope: Resolved): Promise<boolean> {\n const { auth } = this.deps;\n return !auth.enabled() || (await auth.isOrganizationAdmin(c, scope.orgId));\n }\n\n async #list(c: Context, scope: Resolved, routes?: StoredIntakeRouteRecord[]) {\n const registry = await this.#registry(scope);\n routes ??= await this.deps.storage.listIntakeRoutes(scope);\n return c.json({\n intakeRoutes: routes.map(route => present(route, registry)),\n canEdit: await this.#canEdit(c, scope),\n });\n }\n\n /** The project's boards in intake order: the stored order, with any board it lacks slotted in as a new one is. */\n async #intakeOrder(c: Context, scope: Resolved) {\n const registry = await this.#registry(scope);\n const [stored, routes, cards, projectEvaluator] = await Promise.all([\n this.deps.storage.readIntakeOrder(scope, { boards: [...registry.keys()] }),\n this.deps.storage.listIntakeRoutes(scope),\n this.deps.workItems.listShared(scope),\n this.deps.storage.intakeEvaluator(scope),\n ]);\n const forced = this.deps.intakeEvaluator;\n const listed = stored.boardKeys.filter(key => registry.has(key));\n const order = [...listed, ...[...registry.keys()].filter(key => !listed.includes(key))];\n return c.json({\n boards: order.map(boardKey => ({ boardKey, name: registry.get(boardKey)!.name })),\n origin: stored.origin,\n evaluator: forced ?? projectEvaluator ?? 'route-list',\n evaluatorSource: forced ? 'env' : projectEvaluator ? 'project' : 'legacy',\n projectEvaluator,\n // Worked out on every read, so it always describes the order in force and today's rules.\n comparison: compareIntakeOrder({ routes, order, registry, cards }),\n canEdit: await this.#canEdit(c, scope),\n });\n }\n\n #decisionId(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.intakeRouteAgain.pathSchema.safeParse({\n id: c.req.param('id'),\n decisionId: c.req.param('decisionId'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'intake_decision_not_found' });\n return parsed.data.decisionId;\n }\n\n /**\n * Runs intake again for an item no board took. Refuses while no board's rules take it; otherwise\n * commits the item's arrival afresh, so the dispatcher files it as a new arrival would be.\n */\n async #routeAgain(c: Context, scope: Resolved) {\n const { storage, workItems } = this.deps;\n const decision = await storage.getIntakeDecision(scope, this.#decisionId(c));\n if (!decision || decision.outcome !== 'not_routed' || !decision.arrival) {\n throw new Refusal(404, { error: 'intake_decision_not_found' });\n }\n if (decision.resolvedAt) {\n throw new Refusal(409, { error: 'intake_decision_resolved', message: 'This item has been filed since.' });\n }\n const arrival = decision.arrival as unknown as LinkedDecision;\n const [registry, routes] = await Promise.all([this.#registry(scope), storage.listIntakeRoutes(scope)]);\n // Only intake order leaves an item Not routed, so it decides again whatever this replica runs.\n const resolution = resolveIntake({\n evaluator: 'intake-order',\n routes,\n order: await this.#order(scope, registry, 'intake-order'),\n facts: await arrivalRuleFacts(arrival, {\n factoryProjectId: scope.factoryProjectId,\n registry,\n card: id => workItems.get({ orgId: scope.orgId, id }),\n }),\n registry,\n });\n if (resolution.outcome === 'not_routed') {\n throw new Refusal(422, { error: 'intake_not_routed', message: resolution.reason });\n }\n if (resolution.routeId === null) {\n throw new Refusal(422, { error: 'intake_not_routed', message: \"No board's intake rules match it.\" });\n }\n const attempt = `${ROUTE_AGAIN_KEY_PREFIX}${decision.id}:${globalThis.crypto.randomUUID()}`;\n await workItems.commitRuleEvaluation({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n workItemId: null,\n ingress: { identity: attempt },\n expectedRevision: null,\n actor: { type: 'system', id: 'factory-intake-route-again' },\n outcome: { status: 'accepted' },\n decisions: [{ ...arrival, idempotencyKey: attempt }],\n causalChain: [],\n now: new Date(),\n });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake.routed_again',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'intake_decision', id: decision.id, name: decision.title }],\n metadata: { sourceKey: decision.sourceKey, boardKey: resolution.board, routeId: resolution.routeId },\n },\n });\n return c.json(\n { status: 'queued', boardKey: resolution.board, phaseKey: resolution.phase, routeId: resolution.routeId },\n 202,\n );\n }\n\n async #respond(c: Context, scope: Resolved, route: StoredIntakeRouteRecord, status: 200 | 201 = 200) {\n return c.json({ intakeRoute: present(route, await this.#registry(scope)) }, status);\n }\n\n async #audit(\n c: Context,\n scope: Resolved,\n action: 'created' | 'updated' | 'deleted' | 'reordered',\n targets: { id: string; name: string }[],\n ) {\n await this.deps.audit.emit({\n context: c,\n input: {\n action: `factory.intake_route.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: targets.map(route => ({ type: 'intake_route', id: route.id, name: route.name })),\n },\n });\n }\n\n #route(\n contract: { path: string; method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' },\n handle: (c: Context) => Promise<Response>,\n ): ApiRoute {\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n try {\n return await handle(context);\n } catch (error) {\n if (error instanceof Refusal) return context.json(error.body, error.status);\n if (error instanceof IntakeCheckRefusal) {\n return context.json({ error: error.code, message: error.message }, error.status);\n }\n if (error instanceof StoredBoardError) {\n return context.json(\n { error: error.code, message: error.message },\n error.code === 'intake_route_not_found' || error.code === 'intake_decision_not_found'\n ? 404\n : error.code === 'invalid_intake_route' ||\n error.code === 'intake_route_limit' ||\n error.code === 'invalid_intake_cursor'\n ? 422\n : 409,\n );\n }\n throw error;\n }\n },\n });\n }\n\n /** Members read the saved rules; running a draft of them needs the right to edit them. */\n async #check<T extends { boards?: unknown; order?: unknown }>(c: Context, schema: z.ZodType<T>) {\n const scope = await this.#resolve(c);\n const body = await this.#body(c, schema);\n if (isDraft(body)) await this.#requireAdmin(c, scope);\n const check = new IntakeCheck({\n storage: this.deps.storage,\n workItems: this.deps.workItems,\n ...(this.deps.intakeLookups && { lookups: this.deps.intakeLookups }),\n });\n return { scope, body, check, registry: await this.#registry(scope) };\n }\n\n routes(): ApiRoute[] {\n const { storage } = this.deps;\n const contracts = FACTORY_ROUTE_CONTRACTS;\n return [\n this.#route(contracts.intakeDryRun, async c => {\n const { scope, body, check, registry } = await this.#check(c, contracts.intakeDryRun.bodySchema);\n return c.json({\n ...(await check.dryRun(scope, registry, body)),\n evaluator: await this.#evaluator(scope),\n canEdit: await this.#canEdit(c, scope),\n });\n }),\n\n this.#route(contracts.intakeTest, async c => {\n const { scope, body, check, registry } = await this.#check(c, contracts.intakeTest.bodySchema);\n return c.json({ ...(await check.test(scope, registry, body)), evaluator: await this.#evaluator(scope) });\n }),\n\n this.#route(contracts.intakeRouteList, async c => {\n const scope = await this.#resolve(c);\n const query = contracts.intakeRouteList.querySchema.safeParse({ boardKey: c.req.query('boardKey') });\n if (!query.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(query.error.issues) });\n }\n const { boardKey } = query.data;\n return this.#list(\n c,\n scope,\n boardKey === undefined ? undefined : await storage.listIntakeRoutes(scope, { boardKey }),\n );\n }),\n\n this.#route(contracts.intakeOrderGet, async c => this.#intakeOrder(c, await this.#resolve(c))),\n\n this.#route(contracts.intakeOrderUpdate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const { boardKeys, evaluator } = await this.#body(c, contracts.intakeOrderUpdate.bodySchema);\n const registry = await this.#registry(scope);\n const targets = [{ type: 'factory_project', id: scope.factoryProjectId }];\n if (boardKeys) {\n const before = await storage.readIntakeOrder(scope, { boards: [...registry.keys()] });\n await storage.setIntakeOrder(scope, boardKeys, { boards: [...registry.keys()] });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_order.updated',\n factoryProjectId: scope.factoryProjectId,\n targets,\n metadata: { before: before.boardKeys, after: boardKeys },\n },\n });\n }\n if (evaluator) {\n const before = await storage.setIntakeEvaluator(scope, evaluator);\n if (before !== evaluator) {\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_order.evaluator_updated',\n factoryProjectId: scope.factoryProjectId,\n targets,\n metadata: { before, after: evaluator },\n },\n });\n }\n }\n return this.#intakeOrder(c, scope);\n }),\n\n this.#route(contracts.intakeNotRoutedList, async c => {\n const scope = await this.#resolve(c);\n const query = contracts.intakeNotRoutedList.querySchema.safeParse({\n limit: c.req.query('limit'),\n cursor: c.req.query('cursor'),\n });\n if (!query.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(query.error.issues) });\n }\n const page = await storage.listNotRouted(scope, query.data);\n return c.json({\n notRouted: page.notRouted.map(presentDecision),\n nextCursor: page.nextCursor,\n canEdit: await this.#canEdit(c, scope),\n });\n }),\n\n this.#route(contracts.intakeSkippedList, async c => {\n const scope = await this.#resolve(c);\n const summary = await storage.summarizeSkippedByRoute(scope, new Date(Date.now() - SKIPPED_WINDOW_MS));\n return c.json({\n skipped: Object.entries(summary).map(([routeId, { count, latest }]) => ({\n routeId,\n count,\n latest: presentDecision(latest),\n })),\n });\n }),\n\n this.#route(contracts.intakeRouteAgain, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n return this.#routeAgain(c, scope);\n }),\n\n this.#route(contracts.intakeRouteReroutePreview, async c => {\n const scope = await this.#resolve(c);\n const moves = await this.#planReroute(scope);\n return c.json({ total: moves.length, moves: summarizeReroute(moves) });\n }),\n\n this.#route(contracts.intakeRouteRerouteApply, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const moves = await this.#planReroute(scope);\n const result = await applyReroute({\n moves,\n workItems: this.deps.workItems,\n registry: await this.#registry(scope),\n userId: scope.userId,\n });\n await this.deps.audit.emit({\n context: c,\n input: {\n action: 'factory.intake_route.rerouted',\n factoryProjectId: scope.factoryProjectId,\n targets: [...new Set(moves.map(move => move.routeId))].map(id => ({ type: 'intake_route', id })),\n metadata: { ...result, moves: summarizeReroute(moves) },\n },\n });\n return c.json(result);\n }),\n\n this.#route(contracts.intakeRouteReorder, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const { ids, boardKey } = await this.#body(c, contracts.intakeRouteReorder.bodySchema);\n const routes = await storage.reorderIntakeRoutes(\n scope,\n ids,\n scope.userId,\n boardKey === undefined ? {} : { boardKey },\n );\n await this.#audit(c, scope, 'reordered', routes);\n return this.#list(c, scope, routes);\n }),\n\n this.#route(contracts.intakeRouteGet, async c => {\n const scope = await this.#resolve(c);\n const route = await storage.getIntakeRoute(scope, this.#routeId(c));\n if (!route) throw new Refusal(404, { error: 'intake_route_not_found' });\n return this.#respond(c, scope, route);\n }),\n\n this.#route(contracts.intakeRouteCreate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const input = await this.#body(c, contracts.intakeRouteCreate.bodySchema);\n this.#refuseJoin(input.target);\n await this.#checkTarget(scope, {\n target: input.target,\n on: input.on ?? DEFAULT_ROUTE_EVENTS,\n pullRequestOpenedMovesOnly: input.pullRequestOpenedMovesOnly,\n });\n const route = await storage.createIntakeRoute(scope, input, scope.userId);\n await this.#audit(c, scope, 'created', [route]);\n return this.#respond(c, scope, route, 201);\n }),\n\n this.#route(contracts.intakeRouteUpdate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const id = this.#routeId(c);\n const { expectedRevision, ...patch } = await this.#body(c, contracts.intakeRouteUpdate.bodySchema);\n if (patch.target || patch.on) {\n // Narrowing or widening `on` changes which targets are allowed, so check the route as it will be.\n const current = await storage.getIntakeRoute(scope, id);\n if (!current) throw new Refusal(404, { error: 'intake_route_not_found' });\n this.#refuseJoin(patch.target, current.target);\n // Under intake order a rule belongs to its board: it moves with it, never to another.\n if (\n (await this.#evaluator(scope)) === 'intake-order' &&\n patch.target &&\n patch.target.boardKey !== current.target.boardKey\n ) {\n throw new Refusal(422, {\n error: 'intake_route_board_fixed',\n message: `This rule belongs to board \"${current.target.boardKey}\"; add a rule on the other board instead.`,\n });\n }\n // A 0.28 `pull_request.opened` route stays a card move through every edit, `on` included.\n await this.#checkTarget(scope, {\n target: patch.target ?? current.target,\n on: patch.on ?? current.on,\n pullRequestOpenedMovesOnly: current.pullRequestOpenedMovesOnly,\n });\n }\n const route = await storage.updateIntakeRoute(scope, id, patch, { expectedRevision, actor: scope.userId });\n await this.#audit(c, scope, 'updated', [route]);\n return this.#respond(c, scope, route);\n }),\n\n this.#route(contracts.intakeRouteDelete, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const id = this.#routeId(c);\n const parsed = contracts.intakeRouteDelete.querySchema.safeParse({\n expectedRevision: c.req.query('expectedRevision'),\n });\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n const route = await storage.getIntakeRoute(scope, id);\n if (!route) throw new Refusal(404, { error: 'intake_route_not_found' });\n await storage.deleteIntakeRoute(scope, id, { expectedRevision: parsed.data.expectedRevision });\n await this.#audit(c, scope, 'deleted', [route]);\n return c.body(null, 204);\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;AAuEA,SAAS,gBAAgB,UAAsC;CAC7D,MAAM,EAAE,UAAU,SAAS,QAAQ,WAAW,OAAO,KAAK,WAAW,IAAI,SAAS,cAAc;CAChG,OAAO;EAAE;EAAI;EAAS;EAAW;EAAU;EAAS;EAAQ;EAAW;EAAO;EAAK;CAAU;AAC/F;;AAGA,MAAM,oBAAoB;;AAK1B,IAAM,UAAN,MAAc;CAED;CACA;CAFX,YACE,QACA,MACA;EAFS,KAAA,SAAA;EACA,KAAA,OAAA;CACR;AACL;AAEA,SAAS,aAAa,QAA6C;CACjE,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,SAAS,QAAQ,OAAgC,UAAyB;CACxE,MAAM,EAAE,OAAO,QAAQ,kBAAkB,UAAU,GAAG,WAAW;CACjE,MAAM,UAAU,oBAAoB,UAAU,KAAK;CACnD,OAAO;EAAE,GAAG;EAAQ,UAAU,UAAU,CAAC,QAAQ,OAAO,IAAI,CAAC;CAAE;AACjE;AAEA,IA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OAAO,MAAM;IAAO,CAAC;IACzG,MAAM,KAAK,OAAO,GAAG,OAAO,WAAW,CAAC,KAAK,CAAC;IAC9C,OAAO,KAAK,SAAS,GAAG,OAAO,KAAK;GACtC,CAAC;GAED,KAAK,OAAO,UAAU,mBAAmB,OAAM,MAAK;IAClD,MAAM,QAAQ,MAAM,KAAK,SAAS,CAAC;IACnC,MAAM,KAAK,cAAc,GAAG,KAAK;IACjC,MAAM,KAAK,KAAK,SAAS,CAAC;IAC1B,MAAM,SAAS,UAAU,kBAAkB,YAAY,UAAU,EAC/D,kBAAkB,EAAE,IAAI,MAAM,kBAAkB,EAClD,CAAC;IACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,QAAQ,KAAK;KAAE,OAAO;KAAmB,SAAS,aAAa,OAAO,MAAM,MAAM;IAAE,CAAC;IAEjG,MAAM,QAAQ,MAAM,QAAQ,eAAe,OAAO,EAAE;IACpD,IAAI,CAAC,OAAO,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,yBAAyB,CAAC;IACtE,MAAM,QAAQ,kBAAkB,OAAO,IAAI,EAAE,kBAAkB,OAAO,KAAK,iBAAiB,CAAC;IAC7F,MAAM,KAAK,OAAO,GAAG,OAAO,WAAW,CAAC,KAAK,CAAC;IAC9C,OAAO,EAAE,KAAK,MAAM,GAAG;GACzB,CAAC;EACH;CACF;AACF"}
@@ -28,7 +28,7 @@ export interface SkillRoutesDeps extends RouteDependencies {
28
28
  /** Per-project skill edits. Without it the catalog lists originals only and edit routes are not served. */
29
29
  overrides?: {
30
30
  projects: Pick<FactoryProjectsStorage, 'ensureReady' | 'get'>;
31
- storage: Pick<SkillOverridesStorage, 'ensureReady' | 'list' | 'get' | 'upsert' | 'delete'>;
31
+ storage: Pick<SkillOverridesStorage, 'ensureReady' | 'list' | 'get' | 'upsert' | 'create' | 'updateCreated' | 'delete'>;
32
32
  audit: AuditEmitter;
33
33
  };
34
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"skills.d.ts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OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;IACzB,IAAI,CAAC,EAAE,iBAAiB,GAAG,cAAc,GAAG,mBAAmB,CAAC;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAgB,SAAQ,iBAAiB;IACxD,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,YAAY,CAAC,CAAC;IACjE,oBAAoB,CAAC,EAAE,0BAA0B,CAAC;IAClD,wBAAwB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,uBAAuB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,0BAA0B,CAAC,CAAC;IACpH,8GAA8G;IAC9G,MAAM,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,2GAA2G;IAC3G,SAAS,CAAC,EAAE;QACV,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,aAAa,GAAG,KAAK,CAAC,CAAC;QAC9D,OAAO,EAAE,IAAI,CACX,qBAAqB,EACrB,aAAa,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,QAAQ,GAAG,eAAe,GAAG,QAAQ,CAClF,CAAC;QACF,KAAK,EAAE,YAAY,CAAC;KACrB,CAAC;CACH;AA2BD,qBAAa,WAAY,SAAQ,KAAK,CAAC,eAAe,CAAC;;IAgErD,MAAM,IAAI,QAAQ,EAAE,CAsOnB;CACF"}
@@ -1,6 +1,6 @@
1
- import { hashSkillContent, listFactorySkills, readFactorySkillOriginals } from "../skills/catalog.js";
1
+ import { createdSkillInfo, hashSkillContent, listFactorySkills, originalSkillInfo, readFactorySkillOriginals } from "../skills/catalog.js";
2
2
  import { SkillInvocationError, formatSkillMessage, resolveSkillInvocation } from "../skills/service.js";
3
- import { FACTORY_ROUTE_CONTRACTS, skillOverrideSaveRequestSchema } from "./contracts.js";
3
+ import { FACTORY_ROUTE_CONTRACTS, skillCreateBodySchema, skillOverrideSaveRequestSchema } from "./contracts.js";
4
4
  import { Route, loose } from "./route.js";
5
5
  import { registerApiRoute } from "@mastra/core/server";
6
6
  // src/routes/skills.ts
@@ -91,11 +91,6 @@ var SkillRoutes = class extends Route {
91
91
  const { auth } = this.deps;
92
92
  return !auth.enabled() || await auth.isOrganizationAdmin(c, orgId);
93
93
  }
94
- async #catalogEntry(scope, name) {
95
- const { overrides, skills } = this.deps;
96
- const edits = overrides ? await overrides.storage.list(scope) : [];
97
- return (await listFactorySkills(skills, edits)).find((skill) => skill.name === name);
98
- }
99
94
  routes() {
100
95
  const { controllerId, controller, authorizeSessionAddress: customAuthorize } = this.deps;
101
96
  const authorize = customAuthorize ?? ((context, address) => this.#authorizeSessionAddress(context, address));
@@ -195,22 +190,22 @@ var SkillRoutes = class extends Route {
195
190
  message: "Organization administrator access is required to edit skills."
196
191
  }, 403);
197
192
  const name = path.data.name;
198
- const original = (await readFactorySkillOriginals(this.deps.skills)).get(name);
199
- if (!original) return c.json({
200
- error: "not_found",
201
- message: `Skill "${name}" not found.`
202
- }, 404);
203
193
  const scope = {
204
194
  orgId: access.orgId,
205
195
  projectId: access.projectId,
206
196
  skillName: name
207
197
  };
208
198
  await overrides.storage.ensureReady();
199
+ const original = (await readFactorySkillOriginals(this.deps.skills)).get(name);
200
+ if (!original && (await overrides.storage.get(scope))?.kind !== "created") return c.json({
201
+ error: "not_found",
202
+ message: `Skill "${name}" not found.`
203
+ }, 404);
209
204
  if (revert) {
210
205
  if (await overrides.storage.delete(scope)) await overrides.audit.emit({
211
206
  context: c,
212
207
  input: {
213
- action: "factory.skill.reverted",
208
+ action: original ? "factory.skill.reverted" : "factory.skill.deleted",
214
209
  targets: [{
215
210
  type: "skill",
216
211
  id: name
@@ -218,7 +213,7 @@ var SkillRoutes = class extends Route {
218
213
  factoryProjectId: access.projectId
219
214
  }
220
215
  });
221
- return c.json({ skill: await this.#catalogEntry(access, name) });
216
+ return c.json({ skill: original ? originalSkillInfo(name, original) : null });
222
217
  }
223
218
  let body;
224
219
  try {
@@ -237,12 +232,20 @@ var SkillRoutes = class extends Route {
237
232
  error: "invalid_skill",
238
233
  message: request.error.issues.map((issue) => issue.message).join("\n")
239
234
  }, 400);
240
- await overrides.storage.upsert({
235
+ const write = {
241
236
  ...scope,
242
237
  content: request.data.content,
243
- baseHash: hashSkillContent(original.raw),
244
238
  updatedBy: access.userId
245
- });
239
+ };
240
+ const saved = original ? await overrides.storage.upsert({
241
+ ...write,
242
+ baseHash: hashSkillContent(original.raw),
243
+ kind: "edit"
244
+ }) : await overrides.storage.updateCreated(write);
245
+ if (!saved) return c.json({
246
+ error: "not_found",
247
+ message: `Skill "${name}" not found.`
248
+ }, 404);
246
249
  await overrides.audit.emit({
247
250
  context: c,
248
251
  input: {
@@ -252,10 +255,63 @@ var SkillRoutes = class extends Route {
252
255
  id: name
253
256
  }],
254
257
  factoryProjectId: access.projectId,
255
- metadata: { origin: original.origin }
258
+ metadata: { origin: original?.origin ?? "project" }
259
+ }
260
+ });
261
+ return c.json({ skill: original ? originalSkillInfo(name, original, saved) : createdSkillInfo(saved) });
262
+ };
263
+ const handleSkillCreate = async (context) => {
264
+ const c = loose(context);
265
+ const { overrides } = this.deps;
266
+ const path = FACTORY_ROUTE_CONTRACTS.skillCreate.pathSchema.safeParse({ id: c.req.param("id") });
267
+ if (!path.success) return c.json({ error: "Project not found" }, 404);
268
+ const access = await this.#projectAccess(c, path.data.id);
269
+ if ("response" in access) return access.response;
270
+ if (!await this.#canEdit(c, access.orgId)) return c.json({
271
+ error: "forbidden",
272
+ message: "Organization administrator access is required to create skills."
273
+ }, 403);
274
+ let body;
275
+ try {
276
+ body = await c.req.json();
277
+ } catch {
278
+ return c.json({
279
+ error: "invalid_request",
280
+ message: "Invalid JSON body."
281
+ }, 400);
282
+ }
283
+ const request = skillCreateBodySchema.safeParse(body);
284
+ if (!request.success) return c.json({
285
+ error: "invalid_skill",
286
+ message: request.error.issues.map((issue) => issue.message).join("\n")
287
+ }, 400);
288
+ const { name, content } = request.data;
289
+ const exists = {
290
+ error: "skill_exists",
291
+ message: `A skill named "${name}" already exists. Edit it instead.`
292
+ };
293
+ if ((await readFactorySkillOriginals(this.deps.skills)).has(name)) return c.json(exists, 409);
294
+ await overrides.storage.ensureReady();
295
+ const created = await overrides.storage.create({
296
+ orgId: access.orgId,
297
+ projectId: access.projectId,
298
+ skillName: name,
299
+ content,
300
+ updatedBy: access.userId
301
+ });
302
+ if (!created) return c.json(exists, 409);
303
+ await overrides.audit.emit({
304
+ context: c,
305
+ input: {
306
+ action: "factory.skill.created",
307
+ targets: [{
308
+ type: "skill",
309
+ id: name
310
+ }],
311
+ factoryProjectId: access.projectId
256
312
  }
257
313
  });
258
- return c.json({ skill: await this.#catalogEntry(access, name) });
314
+ return c.json({ skill: createdSkillInfo(created) }, 201);
259
315
  };
260
316
  return [
261
317
  registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillList.path, {
@@ -263,15 +319,23 @@ var SkillRoutes = class extends Route {
263
319
  requiresAuth: false,
264
320
  handler: (context) => handleFactorySkillsList(context)
265
321
  }),
266
- ...this.deps.overrides ? [registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillOverrideSave.path, {
267
- method: FACTORY_ROUTE_CONTRACTS.skillOverrideSave.method,
268
- requiresAuth: false,
269
- handler: (context) => handleSkillEdit(context, false)
270
- }), registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillOverrideRevert.path, {
271
- method: FACTORY_ROUTE_CONTRACTS.skillOverrideRevert.method,
272
- requiresAuth: false,
273
- handler: (context) => handleSkillEdit(context, true)
274
- })] : [],
322
+ ...this.deps.overrides ? [
323
+ registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillCreate.path, {
324
+ method: FACTORY_ROUTE_CONTRACTS.skillCreate.method,
325
+ requiresAuth: false,
326
+ handler: (context) => handleSkillCreate(context)
327
+ }),
328
+ registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillOverrideSave.path, {
329
+ method: FACTORY_ROUTE_CONTRACTS.skillOverrideSave.method,
330
+ requiresAuth: false,
331
+ handler: (context) => handleSkillEdit(context, false)
332
+ }),
333
+ registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillOverrideRevert.path, {
334
+ method: FACTORY_ROUTE_CONTRACTS.skillOverrideRevert.method,
335
+ requiresAuth: false,
336
+ handler: (context) => handleSkillEdit(context, true)
337
+ })
338
+ ] : [],
275
339
  registerApiRoute("/web/agent-controller/:controllerId/skills/prepare", {
276
340
  method: "POST",
277
341
  requiresAuth: false,