@mastra/factory 0.28.0-alpha.2 → 0.28.0-alpha.3
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.
- package/README.md +244 -123
- package/dist/boards/board-events.d.ts +23 -3
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +44 -7
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +16 -1
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/card-facts.d.ts +1 -1
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +4 -0
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/default-board.d.ts +7 -0
- package/dist/boards/default-board.d.ts.map +1 -0
- package/dist/boards/default-board.js +10 -0
- package/dist/boards/default-board.js.map +1 -0
- package/dist/boards/define-board.d.ts +39 -17
- package/dist/boards/define-board.d.ts.map +1 -1
- package/dist/boards/define-board.js +64 -42
- package/dist/boards/define-board.js.map +1 -1
- package/dist/boards/index.d.ts +5 -8
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +5 -19
- package/dist/boards/intake-routing.d.ts +27 -5
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +69 -16
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/legacy-plan-role.d.ts.map +1 -1
- package/dist/boards/legacy-plan-role.js +7 -2
- package/dist/boards/legacy-plan-role.js.map +1 -1
- package/dist/boards/phase-automation.d.ts +7 -0
- package/dist/boards/phase-automation.d.ts.map +1 -1
- package/dist/boards/phase-automation.js +16 -5
- package/dist/boards/phase-automation.js.map +1 -1
- package/dist/boards/phase-runner.d.ts +18 -10
- package/dist/boards/phase-runner.d.ts.map +1 -1
- package/dist/boards/phase-runner.js +39 -34
- package/dist/boards/phase-runner.js.map +1 -1
- package/dist/boards/project-boards.d.ts +9 -6
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +56 -18
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/registry.d.ts.map +1 -1
- package/dist/boards/registry.js +3 -1
- package/dist/boards/registry.js.map +1 -1
- package/dist/boards/relocate.d.ts +1 -1
- package/dist/boards/relocate.d.ts.map +1 -1
- package/dist/boards/relocate.js +3 -2
- package/dist/boards/relocate.js.map +1 -1
- package/dist/boards/review.d.ts +5 -2
- package/dist/boards/review.d.ts.map +1 -1
- package/dist/boards/review.js +12 -11
- package/dist/boards/review.js.map +1 -1
- package/dist/boards/semantics.d.ts +159 -20
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +256 -23
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/stored-board.d.ts +32 -18
- package/dist/boards/stored-board.d.ts.map +1 -1
- package/dist/boards/stored-board.js +31 -97
- package/dist/boards/stored-board.js.map +1 -1
- package/dist/boards/work-migrations.d.ts +19 -0
- package/dist/boards/work-migrations.d.ts.map +1 -0
- package/dist/boards/work-migrations.js +257 -0
- package/dist/boards/work-migrations.js.map +1 -0
- package/dist/boards/work-routes.d.ts +53 -0
- package/dist/boards/work-routes.d.ts.map +1 -0
- package/dist/boards/work-routes.js +256 -0
- package/dist/boards/work-routes.js.map +1 -0
- package/dist/boards/work.d.ts +8 -19
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +38 -270
- package/dist/boards/work.js.map +1 -1
- package/dist/factory.d.ts +3 -3
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +58 -30
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -3
- package/dist/integrations/base.d.ts +6 -2
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/closing-references.d.ts +15 -0
- package/dist/integrations/closing-references.d.ts.map +1 -0
- package/dist/integrations/closing-references.js +69 -0
- package/dist/integrations/closing-references.js.map +1 -0
- package/dist/integrations/github/default-rules.d.ts +15 -66
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +129 -71
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +3 -1
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/pull-request-source.d.ts +8 -0
- package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
- package/dist/integrations/github/pull-request-source.js +17 -0
- package/dist/integrations/github/pull-request-source.js.map +1 -0
- package/dist/integrations/github/review-status-reporter.d.ts.map +1 -1
- package/dist/integrations/github/review-status-reporter.js +7 -3
- package/dist/integrations/github/review-status-reporter.js.map +1 -1
- package/dist/integrations/github/routes.js +1 -1
- package/dist/integrations/github/rules.d.ts +13 -2
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +202 -34
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +2 -2
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/token-refresh.d.ts +2 -1
- package/dist/integrations/github/token-refresh.d.ts.map +1 -1
- package/dist/integrations/github/token-refresh.js.map +1 -1
- package/dist/integrations/gitlab/agent-tools.js +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts +73 -31
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +106 -43
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.js +2 -1
- package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +11 -4
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +6 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +116 -23
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/incidentio/agent-tools.js +1 -1
- package/dist/integrations/incidentio/default-rules.js +3 -3
- package/dist/integrations/incidentio/default-rules.js.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.js +2 -1
- package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts +3 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +14 -11
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/jira/agent-tools.js +1 -1
- package/dist/integrations/jira/default-rules.js +3 -3
- package/dist/integrations/jira/default-rules.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js +2 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts +3 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +14 -11
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts +9 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js +80 -2
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/default-rules.js +3 -3
- package/dist/integrations/linear/default-rules.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts +4 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +21 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/linear/issue-reconciler.js +2 -1
- package/dist/integrations/linear/issue-reconciler.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +2 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +4 -3
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +3 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +15 -12
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +33 -21
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/agent-tools.js +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +6 -5
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/slack/chat-tools.js +1 -1
- package/dist/integrations/slack/reply-tool.js +1 -1
- package/dist/integrations/slack/share-file-tool.js +1 -1
- package/dist/integrations/slack/slack.d.ts +10 -4
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +19 -9
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +3 -2
- package/dist/links.js.map +1 -1
- package/dist/mcp/routes.js +2 -2
- package/dist/routes/attention-parked.d.ts +1 -0
- package/dist/routes/attention-parked.d.ts.map +1 -1
- package/dist/routes/attention-parked.js +1 -1
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/automation-runs.d.ts +4 -0
- package/dist/routes/automation-runs.d.ts.map +1 -1
- package/dist/routes/automation-runs.js +15 -0
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/boards.d.ts +1 -1
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js +1 -17
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/config.d.ts +4 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +15 -0
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +125 -14
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +34 -15
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/fs.d.ts +4 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +8 -4
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +1 -0
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +8 -2
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +10 -5
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/running-packages.d.ts +13 -0
- package/dist/routes/running-packages.d.ts.map +1 -0
- package/dist/routes/running-packages.js +45 -0
- package/dist/routes/running-packages.js.map +1 -0
- package/dist/routes/surface.d.ts +10 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +104 -35
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +23 -3
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +1 -0
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +0 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +340 -42
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +33 -2
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +46 -11
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/index.d.ts +2 -4
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -3
- package/dist/rules/phase-goal.d.ts +54 -0
- package/dist/rules/phase-goal.d.ts.map +1 -0
- package/dist/rules/phase-goal.js +70 -0
- package/dist/rules/phase-goal.js.map +1 -0
- package/dist/rules/phase-tools.d.ts +11 -0
- package/dist/rules/phase-tools.d.ts.map +1 -0
- package/dist/rules/phase-tools.js +19 -0
- package/dist/rules/phase-tools.js.map +1 -0
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +112 -11
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/review-source-tool.d.ts +4 -1
- package/dist/rules/review-source-tool.d.ts.map +1 -1
- package/dist/rules/review-source-tool.js +24 -4
- package/dist/rules/review-source-tool.js.map +1 -1
- package/dist/rules/rule-group.d.ts +1 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +2 -1
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +5 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +9 -3
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +39 -28
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +2 -7
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +61 -54
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +83 -29
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +5 -41
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +32 -2
- package/dist/rules/validation.js.map +1 -1
- package/dist/secret-encryption.d.ts +21 -0
- package/dist/secret-encryption.d.ts.map +1 -1
- package/dist/secret-encryption.js +31 -4
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +6 -2
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +8 -4
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/session-threads.d.ts +2 -3
- package/dist/session/session-threads.d.ts.map +1 -1
- package/dist/session/session-threads.js.map +1 -1
- package/dist/session/source-control-tools.js +1 -1
- package/dist/session/work-item-state-processor.d.ts +27 -0
- package/dist/session/work-item-state-processor.d.ts.map +1 -0
- package/dist/session/work-item-state-processor.js +288 -0
- package/dist/session/work-item-state-processor.js.map +1 -0
- package/dist/storage/domains/boards/base.d.ts +44 -27
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +76 -121
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +12 -0
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +32 -2
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +109 -26
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +24 -2
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +118 -8
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
- package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
- package/dist/storage/domains/work-items/legacy-review.js +95 -0
- package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
- package/dist/storage/domains/work-items/metrics.d.ts +12 -4
- package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
- package/dist/storage/domains/work-items/metrics.js +14 -32
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +5 -0
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/tools/approval-tools.d.ts.map +1 -1
- package/dist/tools/approval-tools.js +28 -9
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/messaging-tools.d.ts +3 -0
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +2 -1
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/read-tools.d.ts +8 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +83 -23
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/reports.d.ts +1 -0
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +2 -1
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +1 -1
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +1 -0
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/sandbox-tools.js +1 -1
- package/dist/tools/session-tools.js +1 -1
- package/dist/tools/sessions-state-processor.d.ts +2 -0
- package/dist/tools/sessions-state-processor.d.ts.map +1 -1
- package/dist/tools/sessions-state-processor.js +4 -2
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/dist/tools/side-sessions.d.ts +2 -0
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +2 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/tools/work-item-tools.js +3 -3
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +13 -0
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +16 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts +6 -0
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +25 -1
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/split-migration.d.ts.map +1 -1
- package/dist/work-items/split-migration.js +1 -0
- package/dist/work-items/split-migration.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +53 -10
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +11 -9
- package/factory-skills/factory-build/SKILL.md +64 -0
- package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
- package/factory-skills/factory-gitlab-review/SKILL.md +2 -2
- package/factory-skills/factory-plan/SKILL.md +8 -10
- package/factory-skills/factory-rereview/SKILL.md +3 -3
- package/factory-skills/factory-review/SKILL.md +14 -4
- package/factory-skills/factory-self-review/SKILL.md +31 -11
- package/factory-skills/factory-triage/SKILL.md +25 -10
- package/package.json +10 -10
- package/dist/boards/index.js.map +0 -1
- package/dist/boards/pull-request-review.d.ts +0 -14
- package/dist/boards/pull-request-review.d.ts.map +0 -1
- package/dist/boards/pull-request-review.js +0 -81
- package/dist/boards/pull-request-review.js.map +0 -1
- package/dist/boards/work-tool-rules.d.ts +0 -8
- package/dist/boards/work-tool-rules.d.ts.map +0 -1
- package/dist/boards/work-tool-rules.js +0 -19
- package/dist/boards/work-tool-rules.js.map +0 -1
- package/dist/rules/resolve.d.ts +0 -15
- package/dist/rules/resolve.d.ts.map +0 -1
- package/dist/rules/resolve.js +0 -22
- package/dist/rules/resolve.js.map +0 -1
- package/factory-skills/factory-complete-issue/SKILL.md +0 -24
package/dist/rules/validation.js
CHANGED
|
@@ -84,6 +84,13 @@ function boardEvent(value, label) {
|
|
|
84
84
|
...reason ? { reason } : {}
|
|
85
85
|
};
|
|
86
86
|
}
|
|
87
|
+
function linkedItemReference(value, field) {
|
|
88
|
+
if (value === void 0) return void 0;
|
|
89
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);
|
|
90
|
+
assertExactKeys(value, ["workItemId"], `Factory linked work item ${field}`);
|
|
91
|
+
const { workItemId } = value;
|
|
92
|
+
return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };
|
|
93
|
+
}
|
|
87
94
|
function assertFactoryDecisionTarget(decision, boards, itemBoard) {
|
|
88
95
|
if (decision.type !== "transition" && decision.type !== "upsertLinkedWorkItem") return;
|
|
89
96
|
const board = boards.get(decision.board);
|
|
@@ -91,6 +98,20 @@ function assertFactoryDecisionTarget(decision, boards, itemBoard) {
|
|
|
91
98
|
if (!Object.hasOwn(board.phases, decision.stage)) throw new FactoryRuleValidationError("Factory decision target phase is not defined on its board.");
|
|
92
99
|
if (decision.type === "transition" && itemBoard !== void 0 && itemBoard !== decision.board) throw new FactoryRuleValidationError("Factory transition cannot change the item board.");
|
|
93
100
|
}
|
|
101
|
+
const MAX_GOAL_OBJECTIVE_LENGTH = 2e3;
|
|
102
|
+
const MAX_GOAL_RUNS = 50;
|
|
103
|
+
function invokeSkillGoal(value) {
|
|
104
|
+
if (value === void 0) return void 0;
|
|
105
|
+
if (!isPlainObject(value)) throw new FactoryRuleValidationError("Factory skill goal must be an object.");
|
|
106
|
+
assertExactKeys(value, ["objective", "maxRuns"], "Factory skill goal");
|
|
107
|
+
const objective = boundedString(value.objective, "Factory skill goal objective", MAX_GOAL_OBJECTIVE_LENGTH);
|
|
108
|
+
const { maxRuns } = value;
|
|
109
|
+
if (maxRuns !== void 0 && (typeof maxRuns !== "number" || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)) throw new FactoryRuleValidationError("Factory skill goal maxRuns is invalid.");
|
|
110
|
+
return {
|
|
111
|
+
objective,
|
|
112
|
+
...maxRuns !== void 0 ? { maxRuns } : {}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
94
115
|
function optionalBoundedString(value, label, max) {
|
|
95
116
|
if (value === void 0) return void 0;
|
|
96
117
|
return boundedString(value, label, max);
|
|
@@ -238,12 +259,16 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
238
259
|
"url",
|
|
239
260
|
"stage",
|
|
240
261
|
"skipRules",
|
|
262
|
+
"attachTo",
|
|
263
|
+
"closesIssue",
|
|
241
264
|
"metadata"
|
|
242
265
|
], "Factory linked work item decision");
|
|
243
266
|
if (value.skipRules !== void 0 && typeof value.skipRules !== "boolean") throw new FactoryRuleValidationError("Factory linked work item skipRules must be a boolean.");
|
|
244
267
|
const url = value.url;
|
|
245
268
|
if (url !== null && (typeof url !== "string" || url.length > MAX_URL_LENGTH || !/^https?:\/\//.test(url))) throw new FactoryRuleValidationError("Factory linked work item URL is invalid.");
|
|
246
269
|
const metadata = sanitizeMetadata(value.metadata);
|
|
270
|
+
const attachTo = linkedItemReference(value.attachTo, "attachTo");
|
|
271
|
+
const closesIssue = linkedItemReference(value.closesIssue, "closesIssue");
|
|
247
272
|
return {
|
|
248
273
|
type,
|
|
249
274
|
...commonCommitFields(value),
|
|
@@ -254,6 +279,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
254
279
|
url,
|
|
255
280
|
stage: boardIdentifier(value.stage, "Factory linked work item stage"),
|
|
256
281
|
...value.skipRules === true ? { skipRules: true } : {},
|
|
282
|
+
...attachTo ? { attachTo } : {},
|
|
283
|
+
...closesIssue ? { closesIssue } : {},
|
|
257
284
|
...metadata ? { metadata } : {}
|
|
258
285
|
};
|
|
259
286
|
}
|
|
@@ -268,7 +295,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
268
295
|
"precedingMessage",
|
|
269
296
|
"cancelInFlight",
|
|
270
297
|
"startsAfterOwnMove",
|
|
271
|
-
"resume"
|
|
298
|
+
"resume",
|
|
299
|
+
"goal"
|
|
272
300
|
], "Factory invoke skill decision");
|
|
273
301
|
if (value.skillName === void 0 === (value.prompt === void 0)) throw new FactoryRuleValidationError("Factory skill invocation needs exactly one of skillName or prompt.");
|
|
274
302
|
const args = optionalBoundedString(value.arguments, "Factory skill arguments", MAX_ARGUMENTS_LENGTH);
|
|
@@ -277,6 +305,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
277
305
|
if (value.startsAfterOwnMove !== void 0 && typeof value.startsAfterOwnMove !== "boolean") throw new FactoryRuleValidationError("Factory skill startsAfterOwnMove must be a boolean.");
|
|
278
306
|
if (value.resume !== void 0 && typeof value.resume !== "boolean") throw new FactoryRuleValidationError("Factory skill resume must be a boolean.");
|
|
279
307
|
if (value.resume === true && value.skillName === void 0) throw new FactoryRuleValidationError("Factory skill resume requires skillName.");
|
|
308
|
+
const goal = invokeSkillGoal(value.goal);
|
|
280
309
|
return {
|
|
281
310
|
type,
|
|
282
311
|
...commonCommitFields(value),
|
|
@@ -288,7 +317,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
288
317
|
...args ? { arguments: args } : {},
|
|
289
318
|
...precedingMessage ? { precedingMessage } : {},
|
|
290
319
|
...value.cancelInFlight === true ? { cancelInFlight: true } : {},
|
|
291
|
-
...value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}
|
|
320
|
+
...value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {},
|
|
321
|
+
...goal ? { goal } : {}
|
|
292
322
|
};
|
|
293
323
|
}
|
|
294
324
|
case "sendMessage": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(value, ['type', 'reason'], `${label} event`);\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n return { type, ...(reason ? { reason } : {}) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event'], 'Factory routeEvent decision');\n return { type, ...commonCommitFields(value), event: boardEvent(value.event, 'Factory routeEvent') };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'url',\n 'stage',\n 'skipRules',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,oBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,kBAAuD;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD,OAAgB;CAEhB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,Q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AAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(value, ['type', 'reason'], `${label} event`);\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n return { type, ...(reason ? { reason } : {}) };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event'], 'Factory routeEvent decision');\n return { type, ...commonCommitFields(value), event: boardEvent(value.event, 'Factory routeEvent') };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;A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2BAA2B,4CAA4C;CACrF;AACF;AAEA,SAAgB,6BAA6B,QAA4B,cAAc,GAA4B;CACjH,IAAI,OAAO,SAAS,0BAClB,MAAM,IAAI,2BAA2B,2CAA2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
|
|
@@ -15,6 +15,27 @@ export interface FactorySecretEncryptionConfig {
|
|
|
15
15
|
primary: FactorySecretEncryptionKey;
|
|
16
16
|
previous?: FactorySecretEncryptionKey[];
|
|
17
17
|
}
|
|
18
|
+
/** A stored secret can't be read with the keys this instance was configured with. */
|
|
19
|
+
export declare class FactorySecretDecryptionError extends Error {
|
|
20
|
+
/** True when this instance has no key at all, rather than the wrong one. */
|
|
21
|
+
readonly missingKey: boolean;
|
|
22
|
+
name: string;
|
|
23
|
+
constructor(message: string,
|
|
24
|
+
/** True when this instance has no key at all, rather than the wrong one. */
|
|
25
|
+
missingKey?: boolean);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Client-safe copy for a storage failure caused by an encryption key problem,
|
|
29
|
+
* or `undefined` for any other failure (whose message may expose database
|
|
30
|
+
* internals and stays in the server log). `fix` marks env var names with backticks.
|
|
31
|
+
*/
|
|
32
|
+
export declare function secretKeyProblem(error: unknown): {
|
|
33
|
+
title: string;
|
|
34
|
+
message: string;
|
|
35
|
+
fix: string;
|
|
36
|
+
} | undefined;
|
|
37
|
+
/** {@link secretKeyProblem} as one plain sentence, for API error messages. */
|
|
38
|
+
export declare function secretKeyMismatchHint(error: unknown): string | undefined;
|
|
18
39
|
/**
|
|
19
40
|
* Creates a versioned AES-256-GCM encryptor. The primary key is used for new
|
|
20
41
|
* writes; previous keys remain decrypt-only until stored values are rotated.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;
|
|
1
|
+
{"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAWD,qFAAqF;AACrF,qBAAa,4BAA6B,SAAQ,KAAK;IAKnD,4EAA4E;IAC5E,QAAQ,CAAC,UAAU;IALZ,IAAI,SAAkC;IAE/C,YACE,OAAO,EAAE,MAAM;IACf,4EAA4E;IACnE,UAAU,UAAQ,EAG5B;CACF;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAS5G;AAED,8EAA8E;AAC9E,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAGxE;AAuBD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CA+E5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CAgChF"}
|
|
@@ -10,6 +10,33 @@ function validateKey({ id, key }) {
|
|
|
10
10
|
if (buffer.byteLength !== 32) throw new Error(`[FactorySecretEncryption] Key "${id}" must be exactly 32 bytes.`);
|
|
11
11
|
return buffer;
|
|
12
12
|
}
|
|
13
|
+
/** A stored secret can't be read with the keys this instance was configured with. */
|
|
14
|
+
var FactorySecretDecryptionError = class extends Error {
|
|
15
|
+
missingKey;
|
|
16
|
+
name = "FactorySecretDecryptionError";
|
|
17
|
+
constructor(message, missingKey = false) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.missingKey = missingKey;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Client-safe copy for a storage failure caused by an encryption key problem,
|
|
24
|
+
* or `undefined` for any other failure (whose message may expose database
|
|
25
|
+
* internals and stays in the server log). `fix` marks env var names with backticks.
|
|
26
|
+
*/
|
|
27
|
+
function secretKeyProblem(error) {
|
|
28
|
+
if (!(error instanceof FactorySecretDecryptionError)) return void 0;
|
|
29
|
+
return {
|
|
30
|
+
title: "Factory needs its encryption key",
|
|
31
|
+
message: error.missingKey ? "This deployment doesn't have one set." : "This deployment is using a different one than before.",
|
|
32
|
+
fix: "Set `FACTORY_CREDENTIAL_ENCRYPTION_KEY` and redeploy."
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** {@link secretKeyProblem} as one plain sentence, for API error messages. */
|
|
36
|
+
function secretKeyMismatchHint(error) {
|
|
37
|
+
const problem = secretKeyProblem(error);
|
|
38
|
+
return problem && `${problem.title}. ${problem.message} ${problem.fix.replaceAll("`", "")}`;
|
|
39
|
+
}
|
|
13
40
|
function parseEnvelope(value) {
|
|
14
41
|
let parsed;
|
|
15
42
|
try {
|
|
@@ -68,7 +95,7 @@ function createFactorySecretEncryption(config) {
|
|
|
68
95
|
}
|
|
69
96
|
const envelope = parseEnvelope(value);
|
|
70
97
|
const key = keys.get(envelope.keyId);
|
|
71
|
-
if (!key) throw new
|
|
98
|
+
if (!key) throw new FactorySecretDecryptionError(`[FactorySecretEncryption] Unknown key id "${envelope.keyId}".`);
|
|
72
99
|
let decoded;
|
|
73
100
|
try {
|
|
74
101
|
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, "base64url"));
|
|
@@ -76,7 +103,7 @@ function createFactorySecretEncryption(config) {
|
|
|
76
103
|
const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]).toString("utf8");
|
|
77
104
|
decoded = JSON.parse(plaintext);
|
|
78
105
|
} catch {
|
|
79
|
-
throw new
|
|
106
|
+
throw new FactorySecretDecryptionError("[FactorySecretEncryption] Unable to decrypt encrypted value.");
|
|
80
107
|
}
|
|
81
108
|
const nested = await unwrapNestedEnvelope(decoded, depth);
|
|
82
109
|
if (nested !== void 0) return {
|
|
@@ -125,7 +152,7 @@ function createPlaintextFactorySecretEncryption() {
|
|
|
125
152
|
needsReencryption: true
|
|
126
153
|
};
|
|
127
154
|
}
|
|
128
|
-
throw new
|
|
155
|
+
throw new FactorySecretDecryptionError("[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. Configure 'secretEncryption' with the same key on every Factory instance.", true);
|
|
129
156
|
}
|
|
130
157
|
try {
|
|
131
158
|
return {
|
|
@@ -141,6 +168,6 @@ function createPlaintextFactorySecretEncryption() {
|
|
|
141
168
|
}
|
|
142
169
|
};
|
|
143
170
|
}
|
|
144
|
-
export { createFactorySecretEncryption, createPlaintextFactorySecretEncryption };
|
|
171
|
+
export { FactorySecretDecryptionError, createFactorySecretEncryption, createPlaintextFactorySecretEncryption, secretKeyMismatchHint, secretKeyProblem };
|
|
145
172
|
|
|
146
173
|
//# sourceMappingURL=secret-encryption.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst MAX_NESTED_ENVELOPES = 4;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n decrypt,\n };\n\n async function decrypt<T>(value: unknown, depth = 0): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n return { value: (await unwrapNestedEnvelope<T>(parsed, depth)) ?? (parsed as T), needsReencryption: true };\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n let decoded: unknown;\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n decoded = JSON.parse(plaintext);\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n const nested = await unwrapNestedEnvelope<T>(decoded, depth);\n if (nested !== undefined) return { value: nested, needsReencryption: true };\n return { value: decoded as T, needsReencryption: envelope.keyId !== config.primary.id };\n }\n\n /**\n * Older plaintext encryptors treated an envelope as a raw legacy secret and\n * rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those\n * layers back to the real value so the row is repaired on the next write.\n * A user-supplied secret can also look like an envelope, so anything that\n * does not decrypt with our keys is kept as the literal value.\n */\n async function unwrapNestedEnvelope<T>(value: unknown, depth: number): Promise<T | undefined> {\n if (typeof value !== 'string' || !value.startsWith(ENVELOPE_PREFIX)) return undefined;\n if (depth >= MAX_NESTED_ENVELOPES) return undefined;\n try {\n return (await decrypt<T>(value, depth + 1)).value;\n } catch {\n return undefined;\n }\n }\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n if (value.startsWith(ENVELOPE_PREFIX)) {\n // Never hand an envelope back as the secret, and never let migration\n // rewrite it as plaintext JSON: that corrupts the row for keyed instances.\n // A raw legacy secret can merely start with the prefix; keep those as-is.\n try {\n parseEnvelope(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n throw new Error(\n '[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. ' +\n \"Configure 'secretEncryption' with the same key on every Factory instance.\",\n );\n }\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,uBAAuB;AA8B7B,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QA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AgB,yCAAkE;CAChF,OAAO;EACL,MAAM,QAAW,OAA2B;GAC1C,OAAO,KAAK,UAAU,KAAK;EAC7B;EACA,MAAM,QAAW,OAAoD;GACnE,IAAI,OAAO,UAAU,UAAU,OAAO;IAAE,OAAO,gBAAgB,KAAK;IAAQ,mBAAmB;GAAM;GACrG,IAAI,MAAM,WAAW,eAAe,GAAG;IAIrC,IAAI;KACF,cAAc,KAAK;IACrB,QAAQ;KACN,OAAO;MAAS;MAAY,mBAAmB;KAAK;IACtD;IACA,MAAM,IAAI,MACR,oLAEF;GACF;GACA,IAAI;IACF,OAAO;KAAE,OAAO,KAAK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst MAX_NESTED_ENVELOPES = 4;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\n/** A stored secret can't be read with the keys this instance was configured with. */\nexport class FactorySecretDecryptionError extends Error {\n override name = 'FactorySecretDecryptionError';\n\n constructor(\n message: string,\n /** True when this instance has no key at all, rather than the wrong one. */\n readonly missingKey = false,\n ) {\n super(message);\n }\n}\n\n/**\n * Client-safe copy for a storage failure caused by an encryption key problem,\n * or `undefined` for any other failure (whose message may expose database\n * internals and stays in the server log). `fix` marks env var names with backticks.\n */\nexport function secretKeyProblem(error: unknown): { title: string; message: string; fix: string } | undefined {\n if (!(error instanceof FactorySecretDecryptionError)) return undefined;\n return {\n title: 'Factory needs its encryption key',\n message: error.missingKey\n ? \"This deployment doesn't have one set.\"\n : 'This deployment is using a different one than before.',\n fix: 'Set `FACTORY_CREDENTIAL_ENCRYPTION_KEY` and redeploy.',\n };\n}\n\n/** {@link secretKeyProblem} as one plain sentence, for API error messages. */\nexport function secretKeyMismatchHint(error: unknown): string | undefined {\n const problem = secretKeyProblem(error);\n return problem && `${problem.title}. ${problem.message} ${problem.fix.replaceAll('`', '')}`;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n decrypt,\n };\n\n async function decrypt<T>(value: unknown, depth = 0): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n return { value: (await unwrapNestedEnvelope<T>(parsed, depth)) ?? (parsed as T), needsReencryption: true };\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new FactorySecretDecryptionError(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n let decoded: unknown;\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n decoded = JSON.parse(plaintext);\n } catch {\n throw new FactorySecretDecryptionError('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n const nested = await unwrapNestedEnvelope<T>(decoded, depth);\n if (nested !== undefined) return { value: nested, needsReencryption: true };\n return { value: decoded as T, needsReencryption: envelope.keyId !== config.primary.id };\n }\n\n /**\n * Older plaintext encryptors treated an envelope as a raw legacy secret and\n * rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those\n * layers back to the real value so the row is repaired on the next write.\n * A user-supplied secret can also look like an envelope, so anything that\n * does not decrypt with our keys is kept as the literal value.\n */\n async function unwrapNestedEnvelope<T>(value: unknown, depth: number): Promise<T | undefined> {\n if (typeof value !== 'string' || !value.startsWith(ENVELOPE_PREFIX)) return undefined;\n if (depth >= MAX_NESTED_ENVELOPES) return undefined;\n try {\n return (await decrypt<T>(value, depth + 1)).value;\n } catch {\n return undefined;\n }\n }\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n if (value.startsWith(ENVELOPE_PREFIX)) {\n // Never hand an envelope back as the secret, and never let migration\n // rewrite it as plaintext JSON: that corrupts the row for keyed instances.\n // A raw legacy secret can merely start with the prefix; keep those as-is.\n try {\n parseEnvelope(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n throw new FactorySecretDecryptionError(\n '[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. ' +\n \"Configure 'secretEncryption' with the same key on every Factory instance.\",\n true,\n );\n }\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,uBAAuB;AA8B7B,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;;AAGA,IAAa,+BAAb,cAAkD,MAAM;CAM3C;CALX,OAAgB;CAEhB,YACE,SAEA,aAAsB,OACtB;EACA,MAAM,OAAO;EAFJ,KAAA,aAAA;CAGX;AACF;;;;;;AAOA,SAAgB,iBAAiB,OAA6E;CAC5G,IAAI,EAAE,iBAAiB,+BAA+B,OAAO,KAAA;CAC7D,OAAO;EACL,OAAO;EACP,SAAS,MAAM,aACX,0CACA;EACJ,KAAK;CACP;AACF;;AAGA,SAAgB,sBAAsB,OAAoC;CACxE,MAAM,UAAU,iBAAiB,KAAK;CACtC,OAAO,WAAW,GAAG,QAAQ,MAAM,IAAI,QAAQ,QAAQ,GAAG,QAAQ,IAAI,WAAW,KAAK,EAAE;AAC1F;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD;CACtE;CAEA,IACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAQ,OAA4B,UAAU,YAC9C,OAAQ,OAA4B,OAAO,YAC3C,OAAQ,OAA4B,eAAe,YACnD,OAAQ,OAA4B,QAAQ,UAE5C,MAAM,IAAI,MAAM,oDAAoD;CAEtE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eAAe,GAAG;IAIrC,IAAI;KACF,cAAc,KAAK;IACrB,QAAQ;KACN,OAAO;MAAS;MAAY,mBAAmB;KAAK;IACtD;IACA,MAAM,IAAI,6BACR,sLAEA,IACF;GACF;GACA,IAAI;IACF,OAAO;KAAE,OAAO,KAAK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
2
|
+
import type { ProjectBoardSource } from '../boards/project-boards.js';
|
|
3
|
+
import type { BoardRegistry } from '../boards/registry.js';
|
|
2
4
|
import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
3
5
|
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
4
6
|
/**
|
|
5
|
-
* The head self-review approved for the session's
|
|
6
|
-
*
|
|
7
|
+
* The head self-review approved for the session's card, which a change request must open at.
|
|
8
|
+
* `undefined` leaves the change request ungated (the card's board has no self-review phase);
|
|
9
|
+
* `null` blocks it until self-review approves.
|
|
7
10
|
*/
|
|
8
11
|
export declare function selfReviewApprovedHead(options: {
|
|
9
12
|
requestContext: RequestContext | undefined;
|
|
10
13
|
workItems: WorkItemsStorage;
|
|
11
14
|
projects: FactoryProjectsStorage;
|
|
15
|
+
boards: BoardRegistry | ProjectBoardSource;
|
|
12
16
|
}): Promise<string | null | undefined>;
|
|
13
17
|
//# sourceMappingURL=self-review-gate.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"self-review-gate.d.ts","sourceRoot":"","sources":["../../src/session/self-review-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"self-review-gate.d.ts","sourceRoot":"","sources":["../../src/session/self-review-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAI3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACpD,cAAc,EAAE,cAAc,GAAG,SAAS,CAAC;IAC3C,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAAC;CAC5C,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAqBrC"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { toBoardSource } from "../boards/project-boards.js";
|
|
2
|
+
import { cardBoardFlow, isPullRequestCard } from "../boards/semantics.js";
|
|
2
3
|
import { resolveFactorySessionAddress } from "../rules/binding-context.js";
|
|
3
4
|
import { workItemSource } from "../rules/types.js";
|
|
4
5
|
// src/session/self-review-gate.ts
|
|
5
6
|
/**
|
|
6
|
-
* The head self-review approved for the session's
|
|
7
|
-
*
|
|
7
|
+
* The head self-review approved for the session's card, which a change request must open at.
|
|
8
|
+
* `undefined` leaves the change request ungated (the card's board has no self-review phase);
|
|
9
|
+
* `null` blocks it until self-review approves.
|
|
8
10
|
*/
|
|
9
11
|
async function selfReviewApprovedHead(options) {
|
|
10
12
|
const { requestContext, workItems, projects } = options;
|
|
@@ -19,7 +21,9 @@ async function selfReviewApprovedHead(options) {
|
|
|
19
21
|
orgId: binding.orgId,
|
|
20
22
|
id: binding.workItemId
|
|
21
23
|
});
|
|
22
|
-
if (!item
|
|
24
|
+
if (!item) return void 0;
|
|
25
|
+
const boards = await toBoardSource(options.boards).load(binding);
|
|
26
|
+
if (cardBoardFlow(boards, item).selfReview === void 0) return void 0;
|
|
23
27
|
if (isPullRequestCard({ source: workItemSource(item.externalSource) })) return void 0;
|
|
24
28
|
if (typeof item.metadata?.openPullRequestNumber === "number") return void 0;
|
|
25
29
|
if (item.metadata?.selfReviewVerdict === void 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"self-review-gate.js","names":[],"sources":["../../src/session/self-review-gate.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\n\nimport {
|
|
1
|
+
{"version":3,"file":"self-review-gate.js","names":[],"sources":["../../src/session/self-review-gate.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\n\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { cardBoardFlow, isPullRequestCard } from '../boards/semantics.js';\nimport { resolveFactorySessionAddress } from '../rules/binding-context.js';\nimport { workItemSource } from '../rules/types.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/**\n * The head self-review approved for the session's card, which a change request must open at.\n * `undefined` leaves the change request ungated (the card's board has no self-review phase);\n * `null` blocks it until self-review approves.\n */\nexport async function selfReviewApprovedHead(options: {\n requestContext: RequestContext | undefined;\n workItems: WorkItemsStorage;\n projects: FactoryProjectsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n}): Promise<string | null | undefined> {\n const { requestContext, workItems, projects } = options;\n const resolution = await resolveFactorySessionAddress({ requestContext, storage: workItems });\n if (!resolution) return undefined;\n const binding = resolution.binding ?? (await workItems.findActiveRunBinding(resolution.address));\n if (!binding) return undefined;\n const item = await workItems.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) return undefined;\n const boards = await toBoardSource(options.boards).load(binding);\n if (cardBoardFlow(boards, item).selfReview === undefined) return undefined;\n // A pull request's own card is reviewed, never self-reviewed.\n if (isPullRequestCard({ source: workItemSource(item.externalSource) })) return undefined;\n if (typeof item.metadata?.openPullRequestNumber === 'number') return undefined;\n // A verdict already recorded still binds the change request to its head.\n if (item.metadata?.selfReviewVerdict === undefined) {\n await projects.ensureReady();\n const project = await projects.get({ orgId: binding.orgId, id: binding.factoryProjectId });\n if (!project?.selfReviewEnabled) return undefined;\n }\n const sha = item.metadata?.selfReviewedHeadSha;\n return item.metadata?.selfReviewVerdict === 'approve' && typeof sha === 'string' ? sha : null;\n}\n"],"mappings":";;;;;;;;;;AAgBA,eAAsB,uBAAuB,SAKN;CACrC,MAAM,EAAE,gBAAgB,WAAW,aAAa;CAChD,MAAM,aAAa,MAAM,6BAA6B;EAAE;EAAgB,SAAS;CAAU,CAAC;CAC5F,IAAI,CAAC,YAAY,OAAO,KAAA;CACxB,MAAM,UAAU,WAAW,WAAY,MAAM,UAAU,qBAAqB,WAAW,OAAO;CAC9F,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,OAAO,MAAM,UAAU,IAAI;EAAE,OAAO,QAAQ;EAAO,IAAI,QAAQ;CAAW,CAAC;CACjF,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,SAAS,MAAM,cAAc,QAAQ,MAAM,CAAC,CAAC,KAAK,OAAO;CAC/D,IAAI,cAAc,QAAQ,IAAI,CAAC,CAAC,eAAe,KAAA,GAAW,OAAO,KAAA;CAEjE,IAAI,kBAAkB,EAAE,QAAQ,eAAe,KAAK,cAAc,EAAE,CAAC,GAAG,OAAO,KAAA;CAC/E,IAAI,OAAO,KAAK,UAAU,0BAA0B,UAAU,OAAO,KAAA;CAErE,IAAI,KAAK,UAAU,sBAAsB,KAAA,GAAW;EAClD,MAAM,SAAS,YAAY;EAE3B,IAAI,EAAC,MADiB,SAAS,IAAI;GAAE,OAAO,QAAQ;GAAO,IAAI,QAAQ;EAAiB,CAAC,EAAA,EAC3E,mBAAmB,OAAO,KAAA;CAC1C;CACA,MAAM,MAAM,KAAK,UAAU;CAC3B,OAAO,KAAK,UAAU,sBAAsB,aAAa,OAAO,QAAQ,WAAW,MAAM;AAC3F"}
|
|
@@ -20,7 +20,7 @@ export declare function threadRunBinding(runs: ThreadRunBindings | undefined, th
|
|
|
20
20
|
sessionId: string;
|
|
21
21
|
threadId: string | null | undefined;
|
|
22
22
|
}): Promise<import("../storage/domains/work-items/base.js").FactoryRunBindingRecord | null>;
|
|
23
|
-
type
|
|
23
|
+
export type SessionThreadLookup = Pick<AgentController<any>, 'queryThreadById'>;
|
|
24
24
|
/**
|
|
25
25
|
* The one memory resource a Factory session runs under. A Slack session uses
|
|
26
26
|
* its Factory's, or its sender's for a DM; a side session uses its Factory's,
|
|
@@ -30,7 +30,7 @@ type ThreadLookup = Pick<AgentController<any>, 'queryThreadById'>;
|
|
|
30
30
|
* only for a session with a run binding. A client can create a thread under the
|
|
31
31
|
* session's id, so the thread alone never makes a session the Factory's.
|
|
32
32
|
*/
|
|
33
|
-
export declare function sessionMemoryResourceId(controller:
|
|
33
|
+
export declare function sessionMemoryResourceId(controller: SessionThreadLookup | undefined, session: FactorySessionOwnership, runs: SessionRunBindings | undefined): Promise<string>;
|
|
34
34
|
export declare function isRunBound(session: FactorySessionOwnership, runs: SessionRunBindings | undefined): Promise<boolean>;
|
|
35
35
|
/**
|
|
36
36
|
* A side session works for the session that started it. Otherwise any binding,
|
|
@@ -67,5 +67,4 @@ export declare function sessionStampCounts(session: FactorySessionOwnership, res
|
|
|
67
67
|
* session's memory resource.
|
|
68
68
|
*/
|
|
69
69
|
export declare function listFactorySessionThreads(controller: Pick<AgentController<any>, 'queryThreads' | 'queryThreadById'>, session: FactorySessionOwnership, runs: SessionRunBindings | undefined): Promise<AgentControllerThread[]>;
|
|
70
|
-
export {};
|
|
71
70
|
//# sourceMappingURL=session-threads.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-threads.d.ts","sourceRoot":"","sources":["../../src/session/session-threads.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAE5F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,6EAA6E;AAC7E,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC;AAED,qFAAqF;AACrF,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,gBAAgB,EAAE,yBAAyB,CAAC,CAAC;AAEnF,wFAAwF;AACxF,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;AAEjF,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,iBAAiB,GAAG,SAAS,EACnC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;CAAE,2FAUtG;AAED,
|
|
1
|
+
{"version":3,"file":"session-threads.d.ts","sourceRoot":"","sources":["../../src/session/session-threads.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAE5F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,6EAA6E;AAC7E,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,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AM,GAAG,IAAI,CAAA;CAAE,GAAG,IAAI,GAAG,SAAS,EACtD,QAAQ,EAAE,OAAO,UA4BlB;AAED,yHAAyH;AACzH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,IAAI,CAAC,uBAAuB,EAAE,QAAQ,GAAG,kBAAkB,CAAC,EACrE,UAAU,EAAE,KAAK,GAAG,SAAS,GAC5B,MAAM,CAER;AAED;;;;;GAKG;AACH,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,cAAc,GAAG,iBAAiB,CAAC,EAC1E,OAAO,EAAE,uBAAuB,EAChC,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,EAAE,CAAC,CAUnB;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAEnH;AAED;;;;;;;;GAQG;AACH,wBAAsB,yBAAyB,CAC7C,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,cAAc,GAAG,iBAAiB,CAAC,EAC1E,OAAO,EAAE,uBAAuB,EAChC,IAAI,EAAE,kBAAkB,GAAG,SAAS,GACnC,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAgBlC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-threads.js","names":[],"sources":["../../src/session/session-threads.ts"],"sourcesContent":["import type { AgentController, AgentControllerThread } from '@mastra/core/agent-controller';\n\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/** The Factory session row fields that say which memory resource it uses. */\nexport interface FactorySessionOwnership {\n sessionId: string;\n userId: string;\n orgId?: string;\n factoryProjectId?: string | null;\n branch?: string;\n visibility?: string;\n originSessionId?: string | null;\n}\n\n/** Run bindings: the server-side record that a session runs work for its Factory. */\nexport type SessionRunBindings = Pick<WorkItemsStorage, 'hasRunBindingForSession'>;\n\n/** Run bindings by thread: historical membership, for model and billing policy only. */\nexport type ThreadRunBindings = Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n\nexport async function threadRunBinding(\n runs: ThreadRunBindings | undefined,\n thread: { orgId: string; resourceId: string; sessionId: string; threadId: string | null | undefined },\n) {\n if (!runs || !thread.threadId) return null;\n return runs.findRunBindingByThread({\n orgId: thread.orgId,\n resourceId: thread.resourceId,\n sessionId: thread.sessionId,\n threadId: thread.threadId,\n rejectAmbiguous: true,\n });\n}\n\ntype ThreadLookup = Pick<AgentController<any>, 'queryThreadById'>;\n\n/**\n * The one memory resource a Factory session runs under. A Slack session uses\n * its Factory's, or its sender's for a DM; a side session uses its Factory's,\n * or its owner's when private; any other session uses its owner's. A session's own thread can say otherwise\n * only within what the server recorded for it: its own id (created before\n * resources were shared, or a run kept on its own resource), and the Factory's\n * only for a session with a run binding. A client can create a thread under the\n * session's id, so the thread alone never makes a session the Factory's.\n */\nexport async function sessionMemoryResourceId(\n controller: ThreadLookup | undefined,\n session: FactorySessionOwnership,\n runs: SessionRunBindings | undefined,\n): Promise<string> {\n const [own, runBound] = await Promise.all([\n controller?.queryThreadById({ threadId: session.sessionId }),\n isRunBound(session, runs),\n ]);\n return memoryResourceOf(session, own, runBound);\n}\n\nexport async function isRunBound(session: FactorySessionOwnership, runs: SessionRunBindings | undefined) {\n if (!runs || !session.orgId || !session.factoryProjectId) return false;\n return runs.hasRunBindingForSession({\n orgId: session.orgId,\n factoryProjectId: session.factoryProjectId,\n sessionId: session.sessionId,\n });\n}\n\n/**\n * A side session works for the session that started it. Otherwise any binding,\n * active or revoked, on any thread: a session that ever ran a role stays a worker.\n */\nexport async function isWorkerSession(session: FactorySessionOwnership, runs: SessionRunBindings | undefined) {\n return Boolean(session.originSessionId) || isRunBound(session, runs);\n}\n\n/** {@link sessionMemoryResourceId} for a caller that already loaded the session's own thread. */\nexport function memoryResourceOf(\n session: FactorySessionOwnership,\n own: { resourceId?: string | null } | null | undefined,\n runBound: boolean,\n) {\n const factoryProjectId = session.factoryProjectId ?? undefined;\n const slack = session.branch?.startsWith('slack/') ?? false;\n // A private Slack DM or side session stays with its owner.\n const shared =\n slack || session.originSessionId\n ? session.visibility === 'private'\n ? session.userId\n : factoryProjectId\n : undefined;\n if (shared) {\n if (own?.resourceId && [session.sessionId, shared].includes(own.resourceId)) return own.resourceId;\n return shared;\n }\n // A session a person started runs on their resource while private and its\n // Factory's once its owner shares it, which moves its threads there. Its own\n // thread says where it is; a client cannot make a private session the\n // Factory's by writing that thread, since the Factory is only allowed for a\n // shared or run-bound session.\n const allowed = [\n session.sessionId,\n session.userId,\n ...((runBound || session.visibility === 'org') && factoryProjectId ? [factoryProjectId] : []),\n ];\n if (own?.resourceId && allowed.includes(own.resourceId)) return own.resourceId;\n // No thread yet: where a session with this visibility starts.\n return userSessionResourceFor(session, session.visibility === 'org' ? 'org' : 'private');\n}\n\n/** The resource a person's session belongs on for a visibility: its Factory's once shared, its owner's while private. */\nexport function userSessionResourceFor(\n session: Pick<FactorySessionOwnership, 'userId' | 'factoryProjectId'>,\n visibility: 'org' | 'private',\n): string {\n return visibility === 'org' && session.factoryProjectId ? session.factoryProjectId : session.userId;\n}\n\n/**\n * The threads to move when a person's session changes visibility and so moves\n * onto `resourceId`: its own thread and the threads stamped with its id that\n * sit on its owner's or Factory's resource. Threads under the session's own id\n * (from before resources were shared) stay where they are.\n */\nexport async function sessionThreadsToMove(\n controller: Pick<AgentController<any>, 'queryThreads' | 'queryThreadById'>,\n session: FactorySessionOwnership,\n resourceId: string,\n): Promise<string[]> {\n const movable = new Set([session.userId, ...(session.factoryProjectId ? [session.factoryProjectId] : [])]);\n const [own, stamped] = await Promise.all([\n controller.queryThreadById({ threadId: session.sessionId }),\n controller.queryThreads({ metadata: { factorySessionId: session.sessionId } }),\n ]);\n const threads = [...(own ? [own] : []), ...stamped].filter(\n thread => thread.resourceId !== resourceId && movable.has(thread.resourceId),\n );\n return [...new Set(threads.map(thread => thread.id))];\n}\n\n/**\n * Whether a `factorySessionId` stamp naming this session counts on a thread\n * under `resourceId`. Any org member can write a stamped thread under the\n * Factory's resource, so a private session's stamp never counts there: only\n * its own thread (`thread.id === sessionId`) does.\n */\nexport function sessionStampCounts(session: FactorySessionOwnership, resourceId: string | null | undefined): boolean {\n return !(session.visibility === 'private' && !!session.factoryProjectId && resourceId === session.factoryProjectId);\n}\n\n/**\n * The threads of one Factory session. Sessions share their Factory's or user's\n * resource, so listing by resource would return every session's threads. A\n * session's own thread carries its id, threads it opens are stamped with\n * `factorySessionId`, and a session created before resources were shared keeps\n * its threads under its own id as the resource. Thread ids and stamps are\n * client-writable, so the own and stamped threads only count under the\n * session's memory resource.\n */\nexport async function listFactorySessionThreads(\n controller: Pick<AgentController<any>, 'queryThreads' | 'queryThreadById'>,\n session: FactorySessionOwnership,\n runs: SessionRunBindings | undefined,\n): Promise<AgentControllerThread[]> {\n const { sessionId } = session;\n const [own, runBound, stamped, legacy] = await Promise.all([\n controller.queryThreadById({ threadId: sessionId }),\n isRunBound(session, runs),\n controller.queryThreads({ metadata: { factorySessionId: sessionId } }),\n controller.queryThreads({ resourceId: sessionId }),\n ]);\n const resourceId = memoryResourceOf(session, own, runBound);\n const threads = new Map<string, AgentControllerThread>();\n const owned = [\n ...(own?.resourceId === resourceId ? [own] : []),\n ...(sessionStampCounts(session, resourceId) ? stamped.filter(thread => thread.resourceId === resourceId) : []),\n ];\n for (const thread of [...owned, ...legacy]) threads.set(thread.id, thread);\n return [...threads.values()];\n}\n"],"mappings":";AAqBA,eAAsB,iBACpB,MACA,QACA;CACA,IAAI,CAAC,QAAQ,CAAC,OAAO,UAAU,OAAO;CACtC,OAAO,KAAK,uBAAuB;EACjC,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,WAAW,OAAO;EAClB,UAAU,OAAO;EACjB,iBAAiB;CACnB,CAAC;AACH;;;;;;;;;;AAaA,eAAsB,wBACpB,YACA,SACA,MACiB;CACjB,MAAM,CAAC,KAAK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,OAAO,GAAG,MAAM,GAAG,QAAQ,IAAI,OAAO,IAAI,MAAM;CACzE,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;AAC7B"}
|
|
1
|
+
{"version":3,"file":"session-threads.js","names":[],"sources":["../../src/session/session-threads.ts"],"sourcesContent":["import type { AgentController, AgentControllerThread } from '@mastra/core/agent-controller';\n\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/** The Factory session row fields that say which memory resource it uses. */\nexport interface FactorySessionOwnership {\n sessionId: string;\n userId: string;\n orgId?: string;\n factoryProjectId?: string | null;\n branch?: string;\n visibility?: string;\n originSessionId?: string | null;\n}\n\n/** Run bindings: the server-side record that a session runs work for its Factory. */\nexport type SessionRunBindings = Pick<WorkItemsStorage, 'hasRunBindingForSession'>;\n\n/** Run bindings by thread: historical membership, for model and billing policy only. */\nexport type ThreadRunBindings = Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n\nexport async function threadRunBinding(\n runs: ThreadRunBindings | undefined,\n thread: { orgId: string; resourceId: string; sessionId: string; threadId: string | null | undefined },\n) {\n if (!runs || !thread.threadId) return null;\n return runs.findRunBindingByThread({\n orgId: thread.orgId,\n resourceId: thread.resourceId,\n sessionId: thread.sessionId,\n threadId: thread.threadId,\n rejectAmbiguous: true,\n });\n}\n\nexport type SessionThreadLookup = Pick<AgentController<any>, 'queryThreadById'>;\n\n/**\n * The one memory resource a Factory session runs under. A Slack session uses\n * its Factory's, or its sender's for a DM; a side session uses its Factory's,\n * or its owner's when private; any other session uses its owner's. A session's own thread can say otherwise\n * only within what the server recorded for it: its own id (created before\n * resources were shared, or a run kept on its own resource), and the Factory's\n * only for a session with a run binding. A client can create a thread under the\n * session's id, so the thread alone never makes a session the Factory's.\n */\nexport async function sessionMemoryResourceId(\n controller: SessionThreadLookup | undefined,\n session: FactorySessionOwnership,\n runs: SessionRunBindings | undefined,\n): Promise<string> {\n const [own, runBound] = await Promise.all([\n controller?.queryThreadById({ threadId: session.sessionId }),\n isRunBound(session, runs),\n ]);\n return memoryResourceOf(session, own, runBound);\n}\n\nexport async function isRunBound(session: FactorySessionOwnership, runs: SessionRunBindings | undefined) {\n if (!runs || !session.orgId || !session.factoryProjectId) return false;\n return runs.hasRunBindingForSession({\n orgId: session.orgId,\n factoryProjectId: session.factoryProjectId,\n sessionId: session.sessionId,\n });\n}\n\n/**\n * A side session works for the session that started it. Otherwise any binding,\n * active or revoked, on any thread: a session that ever ran a role stays a worker.\n */\nexport async function isWorkerSession(session: FactorySessionOwnership, runs: SessionRunBindings | undefined) {\n return Boolean(session.originSessionId) || isRunBound(session, runs);\n}\n\n/** {@link sessionMemoryResourceId} for a caller that already loaded the session's own thread. */\nexport function memoryResourceOf(\n session: FactorySessionOwnership,\n own: { resourceId?: string | null } | null | undefined,\n runBound: boolean,\n) {\n const factoryProjectId = session.factoryProjectId ?? undefined;\n const slack = session.branch?.startsWith('slack/') ?? false;\n // A private Slack DM or side session stays with its owner.\n const shared =\n slack || session.originSessionId\n ? session.visibility === 'private'\n ? session.userId\n : factoryProjectId\n : undefined;\n if (shared) {\n if (own?.resourceId && [session.sessionId, shared].includes(own.resourceId)) return own.resourceId;\n return shared;\n }\n // A session a person started runs on their resource while private and its\n // Factory's once its owner shares it, which moves its threads there. Its own\n // thread says where it is; a client cannot make a private session the\n // Factory's by writing that thread, since the Factory is only allowed for a\n // shared or run-bound session.\n const allowed = [\n session.sessionId,\n session.userId,\n ...((runBound || session.visibility === 'org') && factoryProjectId ? [factoryProjectId] : []),\n ];\n if (own?.resourceId && allowed.includes(own.resourceId)) return own.resourceId;\n // No thread yet: where a session with this visibility starts.\n return userSessionResourceFor(session, session.visibility === 'org' ? 'org' : 'private');\n}\n\n/** The resource a person's session belongs on for a visibility: its Factory's once shared, its owner's while private. */\nexport function userSessionResourceFor(\n session: Pick<FactorySessionOwnership, 'userId' | 'factoryProjectId'>,\n visibility: 'org' | 'private',\n): string {\n return visibility === 'org' && session.factoryProjectId ? session.factoryProjectId : session.userId;\n}\n\n/**\n * The threads to move when a person's session changes visibility and so moves\n * onto `resourceId`: its own thread and the threads stamped with its id that\n * sit on its owner's or Factory's resource. Threads under the session's own id\n * (from before resources were shared) stay where they are.\n */\nexport async function sessionThreadsToMove(\n controller: Pick<AgentController<any>, 'queryThreads' | 'queryThreadById'>,\n session: FactorySessionOwnership,\n resourceId: string,\n): Promise<string[]> {\n const movable = new Set([session.userId, ...(session.factoryProjectId ? [session.factoryProjectId] : [])]);\n const [own, stamped] = await Promise.all([\n controller.queryThreadById({ threadId: session.sessionId }),\n controller.queryThreads({ metadata: { factorySessionId: session.sessionId } }),\n ]);\n const threads = [...(own ? [own] : []), ...stamped].filter(\n thread => thread.resourceId !== resourceId && movable.has(thread.resourceId),\n );\n return [...new Set(threads.map(thread => thread.id))];\n}\n\n/**\n * Whether a `factorySessionId` stamp naming this session counts on a thread\n * under `resourceId`. Any org member can write a stamped thread under the\n * Factory's resource, so a private session's stamp never counts there: only\n * its own thread (`thread.id === sessionId`) does.\n */\nexport function sessionStampCounts(session: FactorySessionOwnership, resourceId: string | null | undefined): boolean {\n return !(session.visibility === 'private' && !!session.factoryProjectId && resourceId === session.factoryProjectId);\n}\n\n/**\n * The threads of one Factory session. Sessions share their Factory's or user's\n * resource, so listing by resource would return every session's threads. A\n * session's own thread carries its id, threads it opens are stamped with\n * `factorySessionId`, and a session created before resources were shared keeps\n * its threads under its own id as the resource. Thread ids and stamps are\n * client-writable, so the own and stamped threads only count under the\n * session's memory resource.\n */\nexport async function listFactorySessionThreads(\n controller: Pick<AgentController<any>, 'queryThreads' | 'queryThreadById'>,\n session: FactorySessionOwnership,\n runs: SessionRunBindings | undefined,\n): Promise<AgentControllerThread[]> {\n const { sessionId } = session;\n const [own, runBound, stamped, legacy] = await Promise.all([\n controller.queryThreadById({ threadId: sessionId }),\n isRunBound(session, runs),\n controller.queryThreads({ metadata: { factorySessionId: sessionId } }),\n controller.queryThreads({ resourceId: sessionId }),\n ]);\n const resourceId = memoryResourceOf(session, own, runBound);\n const threads = new Map<string, AgentControllerThread>();\n const owned = [\n ...(own?.resourceId === resourceId ? [own] : []),\n ...(sessionStampCounts(session, resourceId) ? stamped.filter(thread => thread.resourceId === resourceId) : []),\n ];\n for (const thread of [...owned, ...legacy]) threads.set(thread.id, thread);\n return [...threads.values()];\n}\n"],"mappings":";AAqBA,eAAsB,iBACpB,MACA,QACA;CACA,IAAI,CAAC,QAAQ,CAAC,OAAO,UAAU,OAAO;CACtC,OAAO,KAAK,uBAAuB;EACjC,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,WAAW,OAAO;EAClB,UAAU,OAAO;EACjB,iBAAiB;CACnB,CAAC;AACH;;;;;;;;;;AAaA,eAAsB,wBACpB,YACA,SACA,MACiB;CACjB,MAAM,CAAC,KAAK,YAAY,MAAM,QAAQ,IAAI,CACxC,YAAY,gBAAgB,EAAE,UAAU,QAAQ,UAAU,CAAC,GAC3D,WAAW,SAAS,IAAI,CAC1B,CAAC;CACD,OAAO,iBAAiB,SAAS,KAAK,QAAQ;AAChD;AAEA,eAAsB,WAAW,SAAkC,MAAsC;CACvG,IAAI,CAAC,QAAQ,CAAC,QAAQ,SAAS,CAAC,QAAQ,kBAAkB,OAAO;CACjE,OAAO,KAAK,wBAAwB;EAClC,OAAO,QAAQ;EACf,kBAAkB,QAAQ;EAC1B,WAAW,QAAQ;CACrB,CAAC;AACH;;;;;AAMA,eAAsB,gBAAgB,SAAkC,MAAsC;CAC5G,OAAO,QAAQ,QAAQ,eAAe,KAAK,WAAW,SAAS,IAAI;AACrE;;AAGA,SAAgB,iBACd,SACA,KACA,UACA;CACA,MAAM,mBAAmB,QAAQ,oBAAoB,KAAA;CAGrD,MAAM,UAFQ,QAAQ,QAAQ,WAAW,QAAQ,KAAK,UAG3C,QAAQ,kBACb,QAAQ,eAAe,YACrB,QAAQ,SACR,mBACF,KAAA;CACN,IAAI,QAAQ;EACV,IAAI,KAAK,cAAc,CAAC,QAAQ,WAAW,MAAM,CAAC,CAAC,S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AM,QAAQ,IAAI;EACzD,WAAW,gBAAgB,EAAE,UAAU,UAAU,CAAC;EAClD,WAAW,SAAS,IAAI;EACxB,WAAW,aAAa,EAAE,UAAU,EAAE,kBAAkB,UAAU,EAAE,CAAC;EACrE,WAAW,aAAa,EAAE,YAAY,UAAU,CAAC;CACnD,CAAC;CACD,MAAM,aAAa,iBAAiB,SAAS,KAAK,QAAQ;CAC1D,MAAM,0BAAU,IAAI,IAAmC;CACvD,MAAM,QAAQ,CACZ,GAAI,KAAK,eAAe,aAAa,CAAC,GAAG,IAAI,CAAC,GAC9C,GAAI,mBAAmB,SAAS,UAAU,IAAI,QAAQ,QAAO,WAAU,OAAO,eAAe,UAAU,IAAI,CAAC,CAC9G;CACA,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,IAAI,OAAO,IAAI,MAAM;CACzE,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;AAC7B"}
|
|
@@ -5,8 +5,8 @@ import { resolveSessionWorkdir } from "../sandbox/session-sandbox.js";
|
|
|
5
5
|
import { mergeRequestNumberFromBranch } from "../work-item-branch.js";
|
|
6
6
|
import { environmentSlugs, findEnvironmentRepository, resolveSessionRepositories } from "./environment-repositories.js";
|
|
7
7
|
import { updateSessionEnvironmentRepository } from "./environment-state-processor.js";
|
|
8
|
-
import { z } from "zod";
|
|
9
8
|
import { createTool } from "@mastra/core/tools";
|
|
9
|
+
import { z } from "zod";
|
|
10
10
|
// src/session/source-control-tools.ts
|
|
11
11
|
/** Returns why a review's leading `Verdict:` line contradicts the submitted event, if it does. */
|
|
12
12
|
function verdictEventMismatch(event, body) {
|