@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
|
@@ -15,6 +15,14 @@ import type { Card } from './base.js';
|
|
|
15
15
|
export declare const DEFAULT_METRICS_WINDOW = 30;
|
|
16
16
|
/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */
|
|
17
17
|
export declare const MAX_METRICS_WINDOW = 366;
|
|
18
|
+
/**
|
|
19
|
+
* What a card holding `stage` means for flow metrics, read from the card's board: `completed`
|
|
20
|
+
* (an entry feeds throughput and lead time), `canceled` (a tracked non-completion, feeds
|
|
21
|
+
* neither), `queued` (at rest, not yet in flight) or `pipeline` (in flight). Built by
|
|
22
|
+
* `boardPhaseOutcomes`.
|
|
23
|
+
*/
|
|
24
|
+
export type MetricsPhaseOutcome = 'completed' | 'canceled' | 'queued' | 'pipeline';
|
|
25
|
+
export type MetricsPhaseOutcomes = (item: Pick<Card, 'board'>, stage: string) => MetricsPhaseOutcome;
|
|
18
26
|
/**
|
|
19
27
|
* Flow metrics over the cards the Factory ran ({@link hasFactoryRun}) — synced
|
|
20
28
|
* upstream issues and PRs nobody started a run on are not the Factory's work
|
|
@@ -27,18 +35,18 @@ export interface FactoryMetrics {
|
|
|
27
35
|
* drag the per-day rate toward zero on a young board.
|
|
28
36
|
*/
|
|
29
37
|
daysCovered: number;
|
|
30
|
-
/** Entries into
|
|
38
|
+
/** Entries into a completing phase per UTC day, gap-filled across the covered days. */
|
|
31
39
|
throughput: {
|
|
32
40
|
date: string;
|
|
33
41
|
count: number;
|
|
34
42
|
}[];
|
|
35
|
-
/** Card creation →
|
|
43
|
+
/** Card creation → completion for every completion that landed in the window. */
|
|
36
44
|
leadTime: {
|
|
37
45
|
medianMs: number | null;
|
|
38
46
|
p90Ms: number | null;
|
|
39
47
|
samples: number;
|
|
40
48
|
};
|
|
41
|
-
/** Distinct cards in a pipeline stage — past
|
|
49
|
+
/** Distinct cards in a pipeline stage — past rest, not yet terminal. */
|
|
42
50
|
wipTotal: number;
|
|
43
51
|
/** Cards created in the window, by source. */
|
|
44
52
|
sourceMix: {
|
|
@@ -92,6 +100,6 @@ type Window = {
|
|
|
92
100
|
windowStart: number;
|
|
93
101
|
windowEnd: number;
|
|
94
102
|
};
|
|
95
|
-
export declare function computeFactoryMetrics(boardItems: Card[], window: Window): FactoryMetrics;
|
|
103
|
+
export declare function computeFactoryMetrics(boardItems: Card[], window: Window, outcomeOf: MetricsPhaseOutcomes): FactoryMetrics;
|
|
96
104
|
export {};
|
|
97
105
|
//# sourceMappingURL=metrics.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,+EAA+E;AAC/E,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,kFAAkF;AAClF,eAAO,MAAM,kBAAkB,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,+EAA+E;AAC/E,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,kFAAkF;AAClF,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAItC;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,GAAG,UAAU,CAAC;AACnF,MAAM,MAAM,oBAAoB,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,mBAAmB,CAAC;AAYrG;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,uFAAuF;IACvF,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,iFAAiF;IACjF,QAAQ,EAAE;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7E,wEAAwE;IACxE,QAAQ,EAAE,MAAM,CAAC;IACjB,8CAA8C;IAC9C,SAAS,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC/C,2EAA2E;IAC3E,aAAa,EAAE;QACb,KAAK,EAAE,MAAM,CAAC;QACd;;;;;WAKG;QACH,MAAM,EAAE,MAAM,CAAC;QACf;;;;;;WAMG;QACH,OAAO,EAAE,MAAM,CAAC;QAChB;;;;;;WAMG;QACH,QAAQ,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,CAAC;KAClF,EAAE,CAAC;CACL;AAqBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,OAAO,EAClB,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,IAAI,GACR;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAY5C;AA2CD,KAAK,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AAkGzD,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,IAAI,EAAE,EAClB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,oBAAoB,GAC9B,cAAc,CAoBhB"}
|
|
@@ -17,24 +17,6 @@ const DEFAULT_METRICS_WINDOW = 30;
|
|
|
17
17
|
/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */
|
|
18
18
|
const MAX_METRICS_WINDOW = 366;
|
|
19
19
|
const DAY_MS = 864e5;
|
|
20
|
-
/** Terminal stage — items here count as completed, not in-flight. */
|
|
21
|
-
const DONE_STAGE = "done";
|
|
22
|
-
/** Terminal stage for tracked non-completions — never a completion. */
|
|
23
|
-
const CANCELED_STAGE = "canceled";
|
|
24
|
-
/**
|
|
25
|
-
* Terminal stages — items holding only these are not in-flight. `done` is a
|
|
26
|
-
* completion (feeds throughput/lead time); `canceled` is a tracked
|
|
27
|
-
* non-completion outcome and feeds neither.
|
|
28
|
-
*/
|
|
29
|
-
const TERMINAL_STAGES = /* @__PURE__ */ new Set([DONE_STAGE, CANCELED_STAGE]);
|
|
30
|
-
const INTAKE_STAGE = "intake";
|
|
31
|
-
/**
|
|
32
|
-
* Pipeline work excludes the inbox as well as the terminal stages: an intake
|
|
33
|
-
* card is queued, not in flight, and its pass through is the poller filing it.
|
|
34
|
-
*/
|
|
35
|
-
function isPipelineStage(stage) {
|
|
36
|
-
return !TERMINAL_STAGES.has(stage) && stage !== INTAKE_STAGE;
|
|
37
|
-
}
|
|
38
20
|
/**
|
|
39
21
|
* Cards the Factory ran: starting a run records its session on the row. The
|
|
40
22
|
* integrations sync every issue and PR of a connected repo into the board and
|
|
@@ -114,12 +96,12 @@ function stagesHeldAt(item, time) {
|
|
|
114
96
|
}
|
|
115
97
|
/**
|
|
116
98
|
* Completions per UTC day, plus one lead-time sample each. A completion is an
|
|
117
|
-
* entry *into*
|
|
99
|
+
* entry *into* a completing phase, not the state of the card now: a card reopened today
|
|
118
100
|
* must not erase the day it shipped, and a card that shipped twice shipped
|
|
119
101
|
* twice. Days before the oldest card are left out rather than gap-filled with
|
|
120
102
|
* zeroes that would drag the daily average down.
|
|
121
103
|
*/
|
|
122
|
-
function completions(items, { windowStart, windowEnd }) {
|
|
104
|
+
function completions(items, { windowStart, windowEnd }, outcomeOf) {
|
|
123
105
|
let earliestItem = Infinity;
|
|
124
106
|
for (const item of items) earliestItem = Math.min(earliestItem, item.createdAt.getTime());
|
|
125
107
|
const boardStart = Number.isFinite(earliestItem) ? utcDayStart(earliestItem) : -Infinity;
|
|
@@ -127,7 +109,7 @@ function completions(items, { windowStart, windowEnd }) {
|
|
|
127
109
|
for (let day = Math.max(utcDayStart(windowStart), boardStart); day < windowEnd; day += DAY_MS) byDay.set(utcDay(day), 0);
|
|
128
110
|
const leadSamples = [];
|
|
129
111
|
for (const item of items) for (const entry of item.stageHistory) {
|
|
130
|
-
if (entry.stage !==
|
|
112
|
+
if (outcomeOf(item, entry.stage) !== "completed") continue;
|
|
131
113
|
const doneAt = parseTime(entry.enteredAt);
|
|
132
114
|
if (doneAt < windowStart || doneAt >= windowEnd) continue;
|
|
133
115
|
byDay.set(utcDay(doneAt), (byDay.get(utcDay(doneAt)) ?? 0) + 1);
|
|
@@ -139,8 +121,8 @@ function completions(items, { windowStart, windowEnd }) {
|
|
|
139
121
|
};
|
|
140
122
|
}
|
|
141
123
|
/** Cards holding at least one pipeline stage right now — window-independent. */
|
|
142
|
-
function countInFlight(items) {
|
|
143
|
-
return items.filter((item) => item.stages.some(
|
|
124
|
+
function countInFlight(items, outcomeOf) {
|
|
125
|
+
return items.filter((item) => item.stages.some((stage) => outcomeOf(item, stage) === "pipeline")).length;
|
|
144
126
|
}
|
|
145
127
|
/** Where the window's cards came from, most common first. */
|
|
146
128
|
function demandMix(items, { windowStart, windowEnd }) {
|
|
@@ -162,14 +144,14 @@ function demandMix(items, { windowStart, windowEnd }) {
|
|
|
162
144
|
* counted exit; only pipeline stages get rows, since intake and terminal
|
|
163
145
|
* stages have no pass to hand over.
|
|
164
146
|
*/
|
|
165
|
-
function agentCoverage(items, { windowStart, windowEnd }) {
|
|
147
|
+
function agentCoverage(items, { windowStart, windowEnd }, outcomeOf) {
|
|
166
148
|
const byStage = /* @__PURE__ */ new Map();
|
|
167
149
|
for (const item of items) {
|
|
168
|
-
const heldAtWindowEnd = stagesHeldAt(item, windowEnd);
|
|
150
|
+
const heldAtWindowEnd = [...stagesHeldAt(item, windowEnd)].map((stage) => outcomeOf(item, stage));
|
|
169
151
|
const visited = /* @__PURE__ */ new Set();
|
|
170
152
|
for (let i = 0; i < item.stageHistory.length; i++) {
|
|
171
153
|
const entry = item.stageHistory[i];
|
|
172
|
-
if (
|
|
154
|
+
if (outcomeOf(item, entry.stage) !== "pipeline" || visited.has(entry.stage)) continue;
|
|
173
155
|
visited.add(entry.stage);
|
|
174
156
|
if (entry.exitedAt === void 0) continue;
|
|
175
157
|
const exited = parseTime(entry.exitedAt);
|
|
@@ -193,17 +175,17 @@ function agentCoverage(items, { windowStart, windowEnd }) {
|
|
|
193
175
|
if (!isAgentActor(entry.exitedBy)) continue;
|
|
194
176
|
row.byAgent += 1;
|
|
195
177
|
if (item.stageHistory.some((later, j) => j > i && later.stage === entry.stage && parseTime(later.enteredAt) < windowEnd)) row.outcomes.reworked += 1;
|
|
196
|
-
else if (heldAtWindowEnd.
|
|
197
|
-
else if (heldAtWindowEnd.
|
|
178
|
+
else if (heldAtWindowEnd.includes("completed")) row.outcomes.done += 1;
|
|
179
|
+
else if (heldAtWindowEnd.includes("canceled")) row.outcomes.canceled += 1;
|
|
198
180
|
else row.outcomes.inFlight += 1;
|
|
199
181
|
}
|
|
200
182
|
}
|
|
201
183
|
return [...byStage.values()];
|
|
202
184
|
}
|
|
203
|
-
function computeFactoryMetrics(boardItems, window) {
|
|
185
|
+
function computeFactoryMetrics(boardItems, window, outcomeOf) {
|
|
204
186
|
const items = boardItems.filter(hasFactoryRun);
|
|
205
187
|
assertParsableHistory(items);
|
|
206
|
-
const { byDay, leadSamples } = completions(items, window);
|
|
188
|
+
const { byDay, leadSamples } = completions(items, window, outcomeOf);
|
|
207
189
|
return {
|
|
208
190
|
daysCovered: byDay.size,
|
|
209
191
|
throughput: [...byDay.entries()].map(([date, count]) => ({
|
|
@@ -215,9 +197,9 @@ function computeFactoryMetrics(boardItems, window) {
|
|
|
215
197
|
p90Ms: percentile(leadSamples, .9),
|
|
216
198
|
samples: leadSamples.length
|
|
217
199
|
},
|
|
218
|
-
wipTotal: countInFlight(items),
|
|
200
|
+
wipTotal: countInFlight(items, outcomeOf),
|
|
219
201
|
sourceMix: demandMix(items, window),
|
|
220
|
-
agentCoverage: agentCoverage(items, window)
|
|
202
|
+
agentCoverage: agentCoverage(items, window, outcomeOf)
|
|
221
203
|
};
|
|
222
204
|
}
|
|
223
205
|
export { DEFAULT_METRICS_WINDOW, MAX_METRICS_WINDOW, computeFactoryMetrics, parseMetricsRange };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.js","names":[],"sources":["../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Aggregation math for the Factory Overview page.\n *\n * Pure functions over `work_items` rows — throughput, lead time, in-flight\n * count, demand mix and per-stage agent coverage, all read from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n *\n * Everything windowed is counted as an event that happened inside the window,\n * never as \"the state the board happens to be in now\", so re-querying a past\n * window always returns the same numbers.\n */\n\nimport { isAgentActor } from './base.js';\nimport type { Card } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/** Terminal stage — items here count as completed, not in-flight. */\nconst DONE_STAGE = 'done';\n\n/** Terminal stage for tracked non-completions — never a completion. */\nconst CANCELED_STAGE = 'canceled';\n\n/**\n * Terminal stages — items holding only these are not in-flight. `done` is a\n * completion (feeds throughput/lead time); `canceled` is a tracked\n * non-completion outcome and feeds neither.\n */\nconst TERMINAL_STAGES = new Set([DONE_STAGE, CANCELED_STAGE]);\n\nconst INTAKE_STAGE = 'intake';\n\n/**\n * Pipeline work excludes the inbox as well as the terminal stages: an intake\n * card is queued, not in flight, and its pass through is the poller filing it.\n */\nfunction isPipelineStage(stage: string): boolean {\n return !TERMINAL_STAGES.has(stage) && stage !== INTAKE_STAGE;\n}\n\n/**\n * Cards the Factory ran: starting a run records its session on the row. The\n * integrations sync every issue and PR of a connected repo into the board and\n * those outnumber the Factory's own work by an order of magnitude, so counting\n * them reports the upstream repo's flow as the Factory's.\n */\nfunction hasFactoryRun(item: Card): boolean {\n return Object.keys(item.sessions).length > 0;\n}\n\n/**\n * Flow metrics over the cards the Factory ran ({@link hasFactoryRun}) — synced\n * upstream issues and PRs nobody started a run on are not the Factory's work\n * and are excluded from every field below.\n */\nexport interface FactoryMetrics {\n /**\n * Days the series covers: the requested window clipped to the board's life.\n * Days before the first card could hold no completion, so counting them would\n * drag the per-day rate toward zero on a young board.\n */\n daysCovered: number;\n /** Entries into `done` per UTC day, gap-filled across the covered days. */\n throughput: { date: string; count: number }[];\n /** Card creation → `done` for every completion that landed in the window. */\n leadTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Distinct cards in a pipeline stage — past intake, not yet terminal. */\n wipTotal: number;\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Per-stage agent coverage over first visits that ended in the window. */\n agentCoverage: {\n stage: string;\n /**\n * First visits to this stage that ended in the window. Repeat visits are\n * excluded from both sides: they are rework, already reported as such, and\n * counting them in the denominator alone caps a fully agent-run stage below\n * 100%.\n */\n passes: number;\n /**\n * Of those: passes an agent finished (`exitedBy` is an agent actor). The\n * entry actor is not required — the rules engine is what queues a card into\n * a stage, so demanding both ends would report 0% for stages agents run\n * end to end. Missing `exitedBy` (entries written before exit stamping)\n * does not count.\n */\n byAgent: number;\n /**\n * Outcomes of the agent-finished passes' items as of the window's end,\n * mutually exclusive, first match wins: `reworked` (a later visit to the\n * same stage — deliberately outranks `done`: a pass that needed a redo is a\n * failed pass even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\n/** Stage history is server-appended, so an unparsable stamp is a corrupt row. */\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n if (Number.isNaN(time)) throw new Error(`Unparsable stage-history timestamp: ${iso}`);\n return time;\n}\n\n/** Asserted up front so a corrupt row fails every window, not just the ones that read it. */\nfunction assertParsableHistory(items: Card[]): void {\n for (const item of items) {\n for (const entry of item.stageHistory) {\n parseTime(entry.enteredAt);\n if (entry.exitedAt !== undefined) parseTime(entry.exitedAt);\n }\n }\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/** Stages the item was holding at `time`, replayed from its history. */\nfunction stagesHeldAt(item: Card, time: number): Set<string> {\n const held = new Set<string>();\n for (const entry of item.stageHistory) {\n if (parseTime(entry.enteredAt) >= time) continue;\n if (entry.exitedAt !== undefined && parseTime(entry.exitedAt) <= time) continue;\n held.add(entry.stage);\n }\n return held;\n}\n\ntype Window = { windowStart: number; windowEnd: number };\n\n/**\n * Completions per UTC day, plus one lead-time sample each. A completion is an\n * entry *into* `done`, not the state of the card now: a card reopened today\n * must not erase the day it shipped, and a card that shipped twice shipped\n * twice. Days before the oldest card are left out rather than gap-filled with\n * zeroes that would drag the daily average down.\n */\nfunction completions(items: Card[], { windowStart, windowEnd }: Window) {\n let earliestItem = Infinity;\n for (const item of items) earliestItem = Math.min(earliestItem, item.createdAt.getTime());\n const boardStart = Number.isFinite(earliestItem) ? utcDayStart(earliestItem) : -Infinity;\n\n const byDay = new Map<string, number>();\n for (let day = Math.max(utcDayStart(windowStart), boardStart); day < windowEnd; day += DAY_MS) {\n byDay.set(utcDay(day), 0);\n }\n\n const leadSamples: number[] = [];\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (entry.stage !== DONE_STAGE) continue;\n const doneAt = parseTime(entry.enteredAt);\n if (doneAt < windowStart || doneAt >= windowEnd) continue;\n byDay.set(utcDay(doneAt), (byDay.get(utcDay(doneAt)) ?? 0) + 1);\n leadSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n }\n return { byDay, leadSamples };\n}\n\n/** Cards holding at least one pipeline stage right now — window-independent. */\nfunction countInFlight(items: Card[]): number {\n return items.filter(item => item.stages.some(isPipelineStage)).length;\n}\n\n/** Where the window's cards came from, most common first. */\nfunction demandMix(items: Card[], { windowStart, windowEnd }: Window): FactoryMetrics['sourceMix'] {\n const counts = new Map<string, number>();\n for (const item of items) {\n const created = item.createdAt.getTime();\n if (created < windowStart || created >= windowEnd) continue;\n const source = item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual';\n counts.set(source, (counts.get(source) ?? 0) + 1);\n }\n return [...counts.entries()].map(([source, count]) => ({ source, count })).sort((a, b) => b.count - a.count);\n}\n\n/**\n * How much of each stage's work an agent finished, counting a card's first\n * visit to a stage once. Rows appear in insertion order of each stage's first\n * counted exit; only pipeline stages get rows, since intake and terminal\n * stages have no pass to hand over.\n */\nfunction agentCoverage(items: Card[], { windowStart, windowEnd }: Window): FactoryMetrics['agentCoverage'] {\n const byStage = new Map<string, FactoryMetrics['agentCoverage'][number]>();\n for (const item of items) {\n const heldAtWindowEnd = stagesHeldAt(item, windowEnd);\n const visited = new Set<string>();\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (!isPipelineStage(entry.stage) || visited.has(entry.stage)) continue;\n visited.add(entry.stage);\n if (entry.exitedAt === undefined) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n\n let row = byStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n passes: 0,\n byAgent: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n byStage.set(entry.stage, row);\n }\n row.passes += 1;\n if (!isAgentActor(entry.exitedBy)) continue;\n row.byAgent += 1;\n\n const reworked = item.stageHistory.some(\n (later, j) => j > i && later.stage === entry.stage && parseTime(later.enteredAt) < windowEnd,\n );\n if (reworked) row.outcomes.reworked += 1;\n else if (heldAtWindowEnd.has(DONE_STAGE)) row.outcomes.done += 1;\n else if (heldAtWindowEnd.has(CANCELED_STAGE)) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n return [...byStage.values()];\n}\n\nexport function computeFactoryMetrics(boardItems: Card[], window: Window): FactoryMetrics {\n const items = boardItems.filter(hasFactoryRun);\n assertParsableHistory(items);\n\n const { byDay, leadSamples } = completions(items, window);\n\n return {\n daysCovered: byDay.size,\n throughput: [...byDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n leadTime: {\n medianMs: percentile(leadSamples, 0.5),\n p90Ms: percentile(leadSamples, 0.9),\n samples: leadSamples.length,\n },\n wipTotal: countInFlight(items),\n sourceMix: demandMix(items, window),\n agentCoverage: agentCoverage(items, window),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;AAElC,MAAM,SAAS;;AAGf,MAAM,aAAa;;AAGnB,MAAM,iBAAiB;;;;;;AAOvB,MAAM,kCAAkB,IAAI,IAAI,CAAC,YAAY,cAAc,CAAC;AAE5D,MAAM,eAAe;;;;;AAMrB,SAAS,gBAAgB,OAAwB;CAC/C,OAAO,CAAC,gBAAgB,IAAI,KAAK,KAAK,UAAU;AAClD;;;;;;;AAQA,SAAS,cAAc,MAAqB;CAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,SAAS;AAC7C;AAmDA,MAAM,eAAe;;AAErB,MAAM,oBAAoB;AAE1B,SAAS,gBAAgB,OAAgB,UAA6C;CACpF,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,OAAO,KAAA;CAC5D,MAAM,WAAW,aAAa,KAAK,KAAK;CAGxC,IAAI,CAAC,YAAY,CAAC,kBAAkB,KAAK,KAAK,GAAG,OAAO,KAAA;CACxD,MAAM,OAAO,KAAK,MAAM,KAAK;CAC7B,IAAI,OAAO,MAAM,IAAI,GAAG,OAAO,KAAA;CAC/B,OAAO,aAAa,QAAQ,WAAW,OAAO,SAAS;AACzD;AAEA,SAAS,YAAY,MAAsB;CACzC,OAAO,KAAK,MAAM,GAAG,OAAO,IAAI,EAAE,WAAW;AAC/C;;;;;;;AAQA,SAAgB,kBACd,WACA,SACA,KAC4C;CAE5C,MAAM,aAAa,YADL,IAAI,QACiB,CAAC,IAAI;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Ac,GAAG,IAAI,SAAS,YAAY;QAClE,IAAI,SAAS,YAAY;EAChC;CACF;CACA,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;AAC7B;AAEA,SAAgB,sBAAsB,YAAoB,QAAgC;CACxF,MAAM,QAAQ,WAAW,OAAO,aAAa;CAC7C,sBAAsB,KAAK;CAE3B,MAAM,EAAE,OAAO,gBAAgB,YAAY,OAAO,MAAM;CAExD,OAAO;EACL,aAAa,MAAM;EACnB,YAAY,CAAC,GAAG,MAAM,QAAQ,CAAC,CAAC,CAC7B,KAAK,CAAC,MAAM,YAAY;GAAE;GAAM;EAAM,EAAE,CAAC,CACzC,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;EAC9C,UAAU;GACR,UAAU,WAAW,aAAa,EAAG;GACrC,OAAO,WAAW,aAAa,EAAG;GAClC,SAAS,YAAY;EACvB;EACA,UAAU,cAAc,KAAK;EAC7B,WAAW,UAAU,OAAO,MAAM;EAClC,eAAe,cAAc,OAAO,MAAM;CAC5C;AACF"}
|
|
1
|
+
{"version":3,"file":"metrics.js","names":[],"sources":["../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Aggregation math for the Factory Overview page.\n *\n * Pure functions over `work_items` rows — throughput, lead time, in-flight\n * count, demand mix and per-stage agent coverage, all read from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n *\n * Everything windowed is counted as an event that happened inside the window,\n * never as \"the state the board happens to be in now\", so re-querying a past\n * window always returns the same numbers.\n */\n\nimport { isAgentActor } from './base.js';\nimport type { Card } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/**\n * What a card holding `stage` means for flow metrics, read from the card's board: `completed`\n * (an entry feeds throughput and lead time), `canceled` (a tracked non-completion, feeds\n * neither), `queued` (at rest, not yet in flight) or `pipeline` (in flight). Built by\n * `boardPhaseOutcomes`.\n */\nexport type MetricsPhaseOutcome = 'completed' | 'canceled' | 'queued' | 'pipeline';\nexport type MetricsPhaseOutcomes = (item: Pick<Card, 'board'>, stage: string) => MetricsPhaseOutcome;\n\n/**\n * Cards the Factory ran: starting a run records its session on the row. The\n * integrations sync every issue and PR of a connected repo into the board and\n * those outnumber the Factory's own work by an order of magnitude, so counting\n * them reports the upstream repo's flow as the Factory's.\n */\nfunction hasFactoryRun(item: Card): boolean {\n return Object.keys(item.sessions).length > 0;\n}\n\n/**\n * Flow metrics over the cards the Factory ran ({@link hasFactoryRun}) — synced\n * upstream issues and PRs nobody started a run on are not the Factory's work\n * and are excluded from every field below.\n */\nexport interface FactoryMetrics {\n /**\n * Days the series covers: the requested window clipped to the board's life.\n * Days before the first card could hold no completion, so counting them would\n * drag the per-day rate toward zero on a young board.\n */\n daysCovered: number;\n /** Entries into a completing phase per UTC day, gap-filled across the covered days. */\n throughput: { date: string; count: number }[];\n /** Card creation → completion for every completion that landed in the window. */\n leadTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Distinct cards in a pipeline stage — past rest, not yet terminal. */\n wipTotal: number;\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Per-stage agent coverage over first visits that ended in the window. */\n agentCoverage: {\n stage: string;\n /**\n * First visits to this stage that ended in the window. Repeat visits are\n * excluded from both sides: they are rework, already reported as such, and\n * counting them in the denominator alone caps a fully agent-run stage below\n * 100%.\n */\n passes: number;\n /**\n * Of those: passes an agent finished (`exitedBy` is an agent actor). The\n * entry actor is not required — the rules engine is what queues a card into\n * a stage, so demanding both ends would report 0% for stages agents run\n * end to end. Missing `exitedBy` (entries written before exit stamping)\n * does not count.\n */\n byAgent: number;\n /**\n * Outcomes of the agent-finished passes' items as of the window's end,\n * mutually exclusive, first match wins: `reworked` (a later visit to the\n * same stage — deliberately outranks `done`: a pass that needed a redo is a\n * failed pass even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\n/** Stage history is server-appended, so an unparsable stamp is a corrupt row. */\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n if (Number.isNaN(time)) throw new Error(`Unparsable stage-history timestamp: ${iso}`);\n return time;\n}\n\n/** Asserted up front so a corrupt row fails every window, not just the ones that read it. */\nfunction assertParsableHistory(items: Card[]): void {\n for (const item of items) {\n for (const entry of item.stageHistory) {\n parseTime(entry.enteredAt);\n if (entry.exitedAt !== undefined) parseTime(entry.exitedAt);\n }\n }\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/** Stages the item was holding at `time`, replayed from its history. */\nfunction stagesHeldAt(item: Card, time: number): Set<string> {\n const held = new Set<string>();\n for (const entry of item.stageHistory) {\n if (parseTime(entry.enteredAt) >= time) continue;\n if (entry.exitedAt !== undefined && parseTime(entry.exitedAt) <= time) continue;\n held.add(entry.stage);\n }\n return held;\n}\n\ntype Window = { windowStart: number; windowEnd: number };\n\n/**\n * Completions per UTC day, plus one lead-time sample each. A completion is an\n * entry *into* a completing phase, not the state of the card now: a card reopened today\n * must not erase the day it shipped, and a card that shipped twice shipped\n * twice. Days before the oldest card are left out rather than gap-filled with\n * zeroes that would drag the daily average down.\n */\nfunction completions(items: Card[], { windowStart, windowEnd }: Window, outcomeOf: MetricsPhaseOutcomes) {\n let earliestItem = Infinity;\n for (const item of items) earliestItem = Math.min(earliestItem, item.createdAt.getTime());\n const boardStart = Number.isFinite(earliestItem) ? utcDayStart(earliestItem) : -Infinity;\n\n const byDay = new Map<string, number>();\n for (let day = Math.max(utcDayStart(windowStart), boardStart); day < windowEnd; day += DAY_MS) {\n byDay.set(utcDay(day), 0);\n }\n\n const leadSamples: number[] = [];\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (outcomeOf(item, entry.stage) !== 'completed') continue;\n const doneAt = parseTime(entry.enteredAt);\n if (doneAt < windowStart || doneAt >= windowEnd) continue;\n byDay.set(utcDay(doneAt), (byDay.get(utcDay(doneAt)) ?? 0) + 1);\n leadSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n }\n return { byDay, leadSamples };\n}\n\n/** Cards holding at least one pipeline stage right now — window-independent. */\nfunction countInFlight(items: Card[], outcomeOf: MetricsPhaseOutcomes): number {\n return items.filter(item => item.stages.some(stage => outcomeOf(item, stage) === 'pipeline')).length;\n}\n\n/** Where the window's cards came from, most common first. */\nfunction demandMix(items: Card[], { windowStart, windowEnd }: Window): FactoryMetrics['sourceMix'] {\n const counts = new Map<string, number>();\n for (const item of items) {\n const created = item.createdAt.getTime();\n if (created < windowStart || created >= windowEnd) continue;\n const source = item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual';\n counts.set(source, (counts.get(source) ?? 0) + 1);\n }\n return [...counts.entries()].map(([source, count]) => ({ source, count })).sort((a, b) => b.count - a.count);\n}\n\n/**\n * How much of each stage's work an agent finished, counting a card's first\n * visit to a stage once. Rows appear in insertion order of each stage's first\n * counted exit; only pipeline stages get rows, since intake and terminal\n * stages have no pass to hand over.\n */\nfunction agentCoverage(\n items: Card[],\n { windowStart, windowEnd }: Window,\n outcomeOf: MetricsPhaseOutcomes,\n): FactoryMetrics['agentCoverage'] {\n const byStage = new Map<string, FactoryMetrics['agentCoverage'][number]>();\n for (const item of items) {\n const heldAtWindowEnd = [...stagesHeldAt(item, windowEnd)].map(stage => outcomeOf(item, stage));\n const visited = new Set<string>();\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (outcomeOf(item, entry.stage) !== 'pipeline' || visited.has(entry.stage)) continue;\n visited.add(entry.stage);\n if (entry.exitedAt === undefined) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n\n let row = byStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n passes: 0,\n byAgent: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n byStage.set(entry.stage, row);\n }\n row.passes += 1;\n if (!isAgentActor(entry.exitedBy)) continue;\n row.byAgent += 1;\n\n const reworked = item.stageHistory.some(\n (later, j) => j > i && later.stage === entry.stage && parseTime(later.enteredAt) < windowEnd,\n );\n if (reworked) row.outcomes.reworked += 1;\n else if (heldAtWindowEnd.includes('completed')) row.outcomes.done += 1;\n else if (heldAtWindowEnd.includes('canceled')) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n return [...byStage.values()];\n}\n\nexport function computeFactoryMetrics(\n boardItems: Card[],\n window: Window,\n outcomeOf: MetricsPhaseOutcomes,\n): FactoryMetrics {\n const items = boardItems.filter(hasFactoryRun);\n assertParsableHistory(items);\n\n const { byDay, leadSamples } = completions(items, window, outcomeOf);\n\n return {\n daysCovered: byDay.size,\n throughput: [...byDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n leadTime: {\n medianMs: percentile(leadSamples, 0.5),\n p90Ms: percentile(leadSamples, 0.9),\n samples: leadSamples.length,\n },\n wipTotal: countInFlight(items, outcomeOf),\n sourceMix: demandMix(items, window),\n agentCoverage: agentCoverage(items, window, outcomeOf),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,yBAAyB;;AAEtC,MAAa,qBAAqB;AAElC,MAAM,SAAS;;;;;;;AAiBf,SAAS,cAAc,MAAqB;CAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,SAAS;AAC7C;AAmDA,MAAM,eAAe;;AAErB,MAAM,oBAAoB;AAE1B,SAAS,gBAAgB,OAAgB,UAA6C;CACpF,IAAI,OAAO,UAAU,YAAY,MAAM,WA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;CACvD;AACF"}
|
|
@@ -34,11 +34,13 @@ export interface WorkItemSourceDbRecord extends Record<string, unknown> {
|
|
|
34
34
|
labels: string[];
|
|
35
35
|
author: string | null;
|
|
36
36
|
metadata: Record<string, unknown> | null;
|
|
37
|
+
role?: WorkItemSourceRole | null;
|
|
37
38
|
revision: number;
|
|
38
39
|
synced_at: Date | null;
|
|
39
40
|
created_at: Date;
|
|
40
41
|
updated_at: Date;
|
|
41
42
|
}
|
|
43
|
+
export type WorkItemSourceRole = 'origin' | 'attached';
|
|
42
44
|
export interface WorkItemSourceRow {
|
|
43
45
|
id: string;
|
|
44
46
|
workItemId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"work-item-schema.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAEjE,MAAM,MAAM,gBAAgB,GACxB,QAAQ,GACR,QAAQ,GACR,MAAM,GACN,QAAQ,GACR,OAAO,GACP,YAAY,GACZ,SAAS,GACT,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAElB,4EAA4E;AAC5E,eAAO,MAAM,yBAAyB,EAAE,gBAavC,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,gCAAgC,EAAE,
|
|
1
|
+
{"version":3,"file":"work-item-schema.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAEjE,MAAM,MAAM,gBAAgB,GACxB,QAAQ,GACR,QAAQ,GACR,MAAM,GACN,QAAQ,GACR,OAAO,GACP,YAAY,GACZ,SAAS,GACT,C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,CAAC,GAAG,IAAI,CAAC;IACzC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,IAAI,GAAG,IAAI,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;IACjB,wBAAwB,EAAE,IAAI,GAAG,IAAI,CAAC;IACtC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,+FAA+F;AAC/F,eAAO,MAAM,oCAAoC,EAAE,gBAOlD,CAAC;AAEF,mFAAmF;AACnF,eAAO,MAAM,oCAAoC,EAAE,gBAOlD,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,EAAE,gBA8D/B,CAAC;AAEF,6GAA6G;AAC7G,eAAO,MAAM,oCAAoC,EAAE,gBAQlD,CAAC"}
|
|
@@ -64,6 +64,11 @@ const FACTORY_WORK_ITEM_SOURCES_SCHEMA = {
|
|
|
64
64
|
type: "json",
|
|
65
65
|
nullable: true
|
|
66
66
|
},
|
|
67
|
+
/** `origin` for the record the work item was created from, `attached` for one added later. Null (rows written before this column) reads as `origin`. */
|
|
68
|
+
role: {
|
|
69
|
+
type: "text",
|
|
70
|
+
nullable: true
|
|
71
|
+
},
|
|
67
72
|
revision: {
|
|
68
73
|
type: "integer",
|
|
69
74
|
default: 1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"work-item-schema.js","names":[],"sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nimport type { FactoryTriageType } from '../../../rules/types.js';\n\nexport type WorkItemProvider =\n | 'github'\n | 'gitlab'\n | 'jira'\n | 'linear'\n | 'slack'\n | 'incidentio'\n | 'factory'\n | (string & {});\n\n/** The work itself; external identities and facts belong to its sources. */\nexport const FACTORY_WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n title: { type: 'text' },\n parent_work_item_id: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_work_items_org_project_idx', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** Several external records can describe one work item. Native work has no source. */\nexport const FACTORY_WORK_ITEM_SOURCES_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_sources',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n provider: { type: 'text' },\n integration_id: { type: 'text' },\n source_type: { type: 'text' },\n workspace_id: { type: 'text', nullable: true },\n external_id: { type: 'text' },\n source_key: { type: 'text', nullable: true },\n url: { type: 'text', nullable: true },\n key: { type: 'text', nullable: true },\n state: { type: 'text', nullable: true },\n labels: { type: 'json' },\n author: { type: 'text', nullable: true },\n metadata: { type: 'json', nullable: true },\n revision: { type: 'integer', default: 1 },\n synced_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_work_item_sources_project_provider_external_unique',\n columns: ['org_id', 'factory_project_id', 'provider', 'external_id'],\n },\n ],\n indexes: [\n { name: 'factory_work_item_sources_work_item_idx', columns: ['work_item_id'] },\n { name: 'factory_work_item_sources_source_key_idx', columns: ['source_key'] },\n ],\n};\n\n/** Placement/process state. Its id preserves every legacy card reference. */\nexport const FACTORY_BOARD_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_board_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n triage_type: { type: 'text', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n board: { type: 'text', nullable: true },\n parent_board_item_id: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n migrated_from_updated_at: { type: 'timestamp', nullable: true },\n migrated_from_hash: { type: 'text', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_items_work_item_unique', columns: ['work_item_id'] }],\n indexes: [\n {\n name: 'factory_board_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'factory_board_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_board_item_id'],\n },\n ],\n};\n\nexport interface WorkItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n title: string;\n parent_work_item_id: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\nexport interface WorkItemSourceDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n provider: WorkItemProvider;\n integration_id: string;\n source_type: string;\n workspace_id: string | null;\n external_id: string;\n source_key: string | null;\n url: string | null;\n key: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n synced_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nexport interface WorkItemSourceRow {\n id: string;\n workItemId: string;\n provider: WorkItemProvider;\n integrationId: string;\n sourceType: string;\n workspaceId: string | null;\n externalId: string;\n sourceKey: string | null;\n key: string | null;\n url: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function primarySource(card: { workItem: { sources: readonly WorkItemSourceRow[] } }): WorkItemSourceRow | null {\n return card.workItem.sources[0] ?? null;\n}\n\nexport interface WorkItemRow {\n sources: WorkItemSourceRow[];\n id: string;\n orgId: string;\n factoryProjectId: string;\n provider: WorkItemProvider;\n externalId: string;\n key: string | null;\n url: string | null;\n title: string;\n state: string | null;\n labels: string[];\n author: string | null;\n parentWorkItemId: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface BoardItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n triage_type: FactoryTriageType | null;\n accepted_at: Date | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n board: string | null;\n parent_board_item_id: string | null;\n stages: string[];\n stage_history: unknown[];\n sessions: Record<string, unknown>;\n metadata: Record<string, unknown> | null;\n comment_count: number;\n feed_activity_at: Date | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n migrated_from_updated_at: Date | null;\n migrated_from_hash: string | null;\n}\n\n/** Serializes first-copy migration with deletion without locking an entire project's cards. */\nexport const FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** Deleted card ids prevent the boot migration resurrecting frozen legacy rows. */\nexport const FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA: CollectionSchema = {\n name: 'factory_board_item_tombstones',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** The pre-split card table. Frozen: only the split migration reads it. */\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n // Retained for existing tables; claims no longer govern work-item identity.\n claim_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n // Retired hands-off plan grant: plans are approved per board (`exitTool`).\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n {\n // One live card per claimed external record per org. NULL keys never\n // collide, so unclaimed cards are unaffected.\n name: 'work_items_org_claim_key_unique',\n columns: ['org_id', 'claim_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n {\n // Finds the newest legacy write without a scan, so a finished split can be confirmed at boot.\n name: 'work_items_updated_at_id_idx',\n columns: ['updated_at', 'id'],\n },\n ],\n};\n\n/** Records the newest legacy row a finished split pass covered; later boots skip unchanged legacy tables. */\nexport const FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_state',\n columns: {\n id: { type: 'text', primaryKey: true },\n legacy_updated_at: { type: 'timestamp', nullable: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MAAM;GAAa,UAAU;EAAK;EACtD,UAAU;GAAE,MAAM;GAAW,SAAS;EAAE;EACxC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS,CAAC,sBAAsB,YAAY;CAC9C,GACA;EAGE,MAAM;EACN,SAAS,CAAC,UAAU,WAAW;CACjC,CACF;CACA,SAAS;EACP;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;IAAc;GAAI;EAC9D;EACA;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;GAAqB;EACjE;EACA;GAGE,MAAM;GACN,SAAS,CAAC,YAAY;EACxB;EACA;GAEE,MAAM;GACN,SAAS,CAAC,cAAc,IAAI;EAC9B;CACF;AACF;;AAGA,MAAa,uCAAyD;CACpE,MAAM;CACN,SAAS;EACP,IAAI;GAAE,MAAM;GAAQ,YAAY;EAAK;EACrC,mBAAmB;GAAE,MAAM;GAAa,UAAU;EAAK;EACvD,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,cAAc,EAAE,MAAM,YAAY;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"work-item-schema.js","names":[],"sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nimport type { FactoryTriageType } from '../../../rules/types.js';\n\nexport type WorkItemProvider =\n | 'github'\n | 'gitlab'\n | 'jira'\n | 'linear'\n | 'slack'\n | 'incidentio'\n | 'factory'\n | (string & {});\n\n/** The work itself; external identities and facts belong to its sources. */\nexport const FACTORY_WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n title: { type: 'text' },\n parent_work_item_id: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_work_items_org_project_idx', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** Several external records can describe one work item. Native work has no source. */\nexport const FACTORY_WORK_ITEM_SOURCES_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_sources',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n provider: { type: 'text' },\n integration_id: { type: 'text' },\n source_type: { type: 'text' },\n workspace_id: { type: 'text', nullable: true },\n external_id: { type: 'text' },\n source_key: { type: 'text', nullable: true },\n url: { type: 'text', nullable: true },\n key: { type: 'text', nullable: true },\n state: { type: 'text', nullable: true },\n labels: { type: 'json' },\n author: { type: 'text', nullable: true },\n metadata: { type: 'json', nullable: true },\n /** `origin` for the record the work item was created from, `attached` for one added later. Null (rows written before this column) reads as `origin`. */\n role: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n synced_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_work_item_sources_project_provider_external_unique',\n columns: ['org_id', 'factory_project_id', 'provider', 'external_id'],\n },\n ],\n indexes: [\n { name: 'factory_work_item_sources_work_item_idx', columns: ['work_item_id'] },\n { name: 'factory_work_item_sources_source_key_idx', columns: ['source_key'] },\n ],\n};\n\n/** Placement/process state. Its id preserves every legacy card reference. */\nexport const FACTORY_BOARD_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_board_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n triage_type: { type: 'text', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n board: { type: 'text', nullable: true },\n parent_board_item_id: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n migrated_from_updated_at: { type: 'timestamp', nullable: true },\n migrated_from_hash: { type: 'text', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_items_work_item_unique', columns: ['work_item_id'] }],\n indexes: [\n {\n name: 'factory_board_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'factory_board_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_board_item_id'],\n },\n ],\n};\n\nexport interface WorkItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n title: string;\n parent_work_item_id: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\nexport interface WorkItemSourceDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n provider: WorkItemProvider;\n integration_id: string;\n source_type: string;\n workspace_id: string | null;\n external_id: string;\n source_key: string | null;\n url: string | null;\n key: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n role?: WorkItemSourceRole | null;\n revision: number;\n synced_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nexport type WorkItemSourceRole = 'origin' | 'attached';\n\nexport interface WorkItemSourceRow {\n id: string;\n workItemId: string;\n provider: WorkItemProvider;\n integrationId: string;\n sourceType: string;\n workspaceId: string | null;\n externalId: string;\n sourceKey: string | null;\n key: string | null;\n url: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function primarySource(card: { workItem: { sources: readonly WorkItemSourceRow[] } }): WorkItemSourceRow | null {\n return card.workItem.sources[0] ?? null;\n}\n\nexport interface WorkItemRow {\n sources: WorkItemSourceRow[];\n id: string;\n orgId: string;\n factoryProjectId: string;\n provider: WorkItemProvider;\n externalId: string;\n key: string | null;\n url: string | null;\n title: string;\n state: string | null;\n labels: string[];\n author: string | null;\n parentWorkItemId: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface BoardItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n triage_type: FactoryTriageType | null;\n accepted_at: Date | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n board: string | null;\n parent_board_item_id: string | null;\n stages: string[];\n stage_history: unknown[];\n sessions: Record<string, unknown>;\n metadata: Record<string, unknown> | null;\n comment_count: number;\n feed_activity_at: Date | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n migrated_from_updated_at: Date | null;\n migrated_from_hash: string | null;\n}\n\n/** Serializes first-copy migration with deletion without locking an entire project's cards. */\nexport const FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** Deleted card ids prevent the boot migration resurrecting frozen legacy rows. */\nexport const FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA: CollectionSchema = {\n name: 'factory_board_item_tombstones',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** The pre-split card table. Frozen: only the split migration reads it. */\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n // Retained for existing tables; claims no longer govern work-item identity.\n claim_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n // Retired hands-off plan grant: plans are approved per board (`exitTool`).\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n {\n // One live card per claimed external record per org. NULL keys never\n // collide, so unclaimed cards are unaffected.\n name: 'work_items_org_claim_key_unique',\n columns: ['org_id', 'claim_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n {\n // Finds the newest legacy write without a scan, so a finished split can be confirmed at boot.\n name: 'work_items_updated_at_id_idx',\n columns: ['updated_at', 'id'],\n },\n ],\n};\n\n/** Records the newest legacy row a finished split pass covered; later boots skip unchanged legacy tables. */\nexport const FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_state',\n columns: {\n id: { type: 'text', primaryKey: true },\n legacy_updated_at: { type: 'timestamp', nullable: true },\n legacy_id: { type: 'text',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AE;EAC7C,kBAAkB;GAAE,MAAM;GAAa,UAAU;EAAK;EACtD,UAAU;GAAE,MAAM;GAAW,SAAS;EAAE;EACxC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS,CAAC,sBAAsB,YAAY;CAC9C,GACA;EAGE,MAAM;EACN,SAAS,CAAC,UAAU,WAAW;CACjC,CACF;CACA,SAAS;EACP;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;IAAc;GAAI;EAC9D;EACA;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;GAAqB;EACjE;EACA;GAGE,MAAM;GACN,SAAS,CAAC,YAAY;EACxB;EACA;GAEE,MAAM;GACN,SAAS,CAAC,cAAc,IAAI;EAC9B;CACF;AACF;;AAGA,MAAa,uCAAyD;CACpE,MAAM;CACN,SAAS;EACP,IAAI;GAAE,MAAM;GAAQ,YAAY;EAAK;EACrC,mBAAmB;GAAE,MAAM;GAAa,UAAU;EAAK;EACvD,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,cAAc,EAAE,MAAM,YAAY;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-tools.d.ts","sourceRoot":"","sources":["../../src/tools/approval-tools.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"approval-tools.d.ts","sourceRoot":"","sources":["../../src/tools/approval-tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,WAAW,+BAA+B;IAC9C,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;IAC7D,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,gCAAgC,GAAG,0BAA0B,CAAC,CAAC;IACjG,aAAa,EAAE,aAAa,CAAC;IAC7B,SAAS,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC;CACnD;AAkBD,yGAAyG;AACzG,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,+BAA+B,GACpC,gBAAgB,CAoGlB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { requirePerson } from "./scope.js";
|
|
2
|
-
import {
|
|
2
|
+
import { RequestContext } from "@mastra/core/request-context";
|
|
3
3
|
import { createTool } from "@mastra/core/tools";
|
|
4
|
+
import { z } from "zod";
|
|
4
5
|
// src/tools/approval-tools.ts
|
|
5
6
|
/** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */
|
|
6
7
|
function createFactoryApprovalTools(scope, deps) {
|
|
@@ -8,7 +9,8 @@ function createFactoryApprovalTools(scope, deps) {
|
|
|
8
9
|
id: "factory_answer_approval",
|
|
9
10
|
description: [
|
|
10
11
|
"Approve or decline a tool call a session you follow is waiting on, as you.",
|
|
11
|
-
"A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId
|
|
12
|
+
"A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId;",
|
|
13
|
+
"a `blocked` notice for a session parked on submit_plan names the toolCallId of the plan to approve or decline.",
|
|
12
14
|
"Answer only what the person in this conversation agreed to; decline with a reason the session will see."
|
|
13
15
|
].join(" "),
|
|
14
16
|
inputSchema: z.object({
|
|
@@ -37,13 +39,30 @@ function createFactoryApprovalTools(scope, deps) {
|
|
|
37
39
|
const messaging = await deps.messaging();
|
|
38
40
|
if (!messaging) throw new Error("Answering approvals is not available on this server.");
|
|
39
41
|
const live = await messaging.controller.getSession(sessionId);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
const parkedPlan = live?.suspensions.resolve({ toolCallId })?.toolName === "submit_plan";
|
|
43
|
+
if (!live || !parkedPlan && !live.approval.isArmed({ toolCallId })) throw new Error("Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. Message the session with factory_signal_session if it should try again.");
|
|
44
|
+
if (parkedPlan) {
|
|
45
|
+
const requestContext = new RequestContext();
|
|
46
|
+
requestContext.set("user", {
|
|
47
|
+
workosId: scope.userId,
|
|
48
|
+
organizationId: scope.orgId
|
|
49
|
+
});
|
|
50
|
+
await live.respondToToolSuspension({
|
|
51
|
+
resumeData: decision === "approve" ? { action: "approved" } : {
|
|
52
|
+
action: "rejected",
|
|
53
|
+
feedback: reason ?? "Declined by a session following it."
|
|
54
|
+
},
|
|
55
|
+
toolCallId,
|
|
56
|
+
requestContext
|
|
57
|
+
});
|
|
58
|
+
} else {
|
|
59
|
+
const result = live.respondToToolApproval({
|
|
60
|
+
decision,
|
|
61
|
+
toolCallId,
|
|
62
|
+
...decision === "decline" ? { declineContext: { reason: reason ?? "Declined by a session following it." } } : {}
|
|
63
|
+
});
|
|
64
|
+
if (!result.accepted) throw new Error(`The answer was not accepted (${result.reason}).`);
|
|
65
|
+
}
|
|
47
66
|
deps.auditRecorder.record({
|
|
48
67
|
orgId: scope.orgId,
|
|
49
68
|
actorId: scope.userId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-tools.js","names":[],"sources":["../../src/tools/approval-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryApprovalToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findActiveRunBindingForSession' | 'listSessionSubscriptions'>;\n auditRecorder: AuditRecorder;\n messaging: () => Promise<FactoryMessaging | null>;\n}\n\n/** The parts of a live session an answer needs: its open approval gates. */\ninterface ApprovalGateSession {\n approval: { isArmed(filter: { toolCallId: string }): boolean };\n respondToToolApproval(input: {\n decision: 'approve' | 'decline';\n toolCallId: string;\n declineContext?: { reason?: string };\n }): { accepted: true } | { accepted: false; reason: string };\n}\n\n/** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */\nexport function createFactoryApprovalTools(\n scope: FactoryToolScope,\n deps: FactoryApprovalToolDependencies,\n): IntegrationTools {\n const answer = createTool({\n id: 'factory_answer_approval',\n description: [\n 'Approve or decline a tool call a session you follow is waiting on, as you.',\n 'A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId.',\n 'Answer only what the person in this conversation agreed to; decline with a reason the session will see.',\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().uuid().describe('The session holding the call, from the approval notice.'),\n toolCallId: z.string().trim().min(1).max(200),\n decision: z.enum(['approve', 'decline']),\n reason: z.string().trim().min(1).max(1000).optional().describe('Why, when declining.'),\n })\n .strict(),\n execute: async ({ sessionId, toolCallId, decision, reason }) => {\n requirePerson(scope, 'answer an approval');\n const row = await deps.sessions.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) {\n throw new Error(`Session ${sessionId} was not found in this Factory.`);\n }\n if (row.visibility === 'private' && row.userId !== scope.userId) {\n throw new Error(`Session ${sessionId} is private to its owner.`);\n }\n\n // Only the sessions it reports to may answer it: its origin, or followers of its item.\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n });\n const isOrigin = row.originSessionId === scope.sessionId;\n const follows =\n binding !== null &&\n (\n await deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n })\n ).some(subscription => subscription.workItemId === binding.workItemId);\n if (!isOrigin && !follows) {\n throw new Error(\n `This session doesn't follow session ${sessionId}: follow its work item first, or answer from that session.`,\n );\n }\n\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Answering approvals is not available on this server.');\n const live = (await messaging.controller.getSession(sessionId)) as ApprovalGateSession | null;\n if (!live
|
|
1
|
+
{"version":3,"file":"approval-tools.js","names":[],"sources":["../../src/tools/approval-tools.ts"],"sourcesContent":["import { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryApprovalToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findActiveRunBindingForSession' | 'listSessionSubscriptions'>;\n auditRecorder: AuditRecorder;\n messaging: () => Promise<FactoryMessaging | null>;\n}\n\n/** The parts of a live session an answer needs: its open approval gates. */\ninterface ApprovalGateSession {\n approval: { isArmed(filter: { toolCallId: string }): boolean };\n respondToToolApproval(input: {\n decision: 'approve' | 'decline';\n toolCallId: string;\n declineContext?: { reason?: string };\n }): { accepted: true } | { accepted: false; reason: string };\n suspensions: { resolve(filter: { toolCallId: string }): { toolName: string } | undefined };\n respondToToolSuspension(input: {\n resumeData: { action: 'approved' | 'rejected'; feedback?: string };\n toolCallId: string;\n requestContext?: RequestContext;\n }): Promise<void>;\n}\n\n/** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */\nexport function createFactoryApprovalTools(\n scope: FactoryToolScope,\n deps: FactoryApprovalToolDependencies,\n): IntegrationTools {\n const answer = createTool({\n id: 'factory_answer_approval',\n description: [\n 'Approve or decline a tool call a session you follow is waiting on, as you.',\n 'A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId;',\n 'a `blocked` notice for a session parked on submit_plan names the toolCallId of the plan to approve or decline.',\n 'Answer only what the person in this conversation agreed to; decline with a reason the session will see.',\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().uuid().describe('The session holding the call, from the approval notice.'),\n toolCallId: z.string().trim().min(1).max(200),\n decision: z.enum(['approve', 'decline']),\n reason: z.string().trim().min(1).max(1000).optional().describe('Why, when declining.'),\n })\n .strict(),\n execute: async ({ sessionId, toolCallId, decision, reason }) => {\n requirePerson(scope, 'answer an approval');\n const row = await deps.sessions.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) {\n throw new Error(`Session ${sessionId} was not found in this Factory.`);\n }\n if (row.visibility === 'private' && row.userId !== scope.userId) {\n throw new Error(`Session ${sessionId} is private to its owner.`);\n }\n\n // Only the sessions it reports to may answer it: its origin, or followers of its item.\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n });\n const isOrigin = row.originSessionId === scope.sessionId;\n const follows =\n binding !== null &&\n (\n await deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n })\n ).some(subscription => subscription.workItemId === binding.workItemId);\n if (!isOrigin && !follows) {\n throw new Error(\n `This session doesn't follow session ${sessionId}: follow its work item first, or answer from that session.`,\n );\n }\n\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Answering approvals is not available on this server.');\n const live = (await messaging.controller.getSession(sessionId)) as ApprovalGateSession | null;\n const parkedPlan = live?.suspensions.resolve({ toolCallId })?.toolName === 'submit_plan';\n if (!live || (!parkedPlan && !live.approval.isArmed({ toolCallId }))) {\n throw new Error(\n 'Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. ' +\n 'Message the session with factory_signal_session if it should try again.',\n );\n }\n if (parkedPlan) {\n // The resumed run acts for the person answering, so it can resolve their model credentials.\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: scope.userId, organizationId: scope.orgId });\n await live.respondToToolSuspension({\n resumeData:\n decision === 'approve'\n ? { action: 'approved' }\n : { action: 'rejected', feedback: reason ?? 'Declined by a session following it.' },\n toolCallId,\n requestContext,\n });\n } else {\n const result = live.respondToToolApproval({\n decision,\n toolCallId,\n ...(decision === 'decline'\n ? { declineContext: { reason: reason ?? 'Declined by a session following it.' } }\n : {}),\n });\n if (!result.accepted) throw new Error(`The answer was not accepted (${result.reason}).`);\n }\n\n deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: scope.userId,\n actorType: 'human',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n action: decision === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n factoryProjectId: scope.factoryProjectId,\n targets: [\n { type: 'session', id: sessionId },\n ...(binding ? [{ type: 'work_item' as const, id: binding.workItemId }] : []),\n ],\n metadata: { toolCallId, sessionId, decision, cause: 'factory_tools' },\n });\n return { answered: decision, sessionId, toolCallId };\n },\n });\n\n return { factory_answer_approval: answer };\n}\n"],"mappings":";;;;;;AAoCA,SAAgB,2BACd,OACA,MACkB;CAmGlB,OAAO,EAAE,yBAlGM,WAAW;EACxB,IAAI;EACJ,aAAa;GACX;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,GAAG;EACV,aAAa,EACV,OAAO;GACN,WAAW,EAAE,OAAO,CAAC,CAAC,K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AAE,WAAW,CAAC,CAAC,EAAE,aAAa;GAC3E,IAAI,CAAC,QAAS,CAAC,cAAc,CAAC,KAAK,SAAS,QAAQ,EAAE,WAAW,CAAC,GAChE,MAAM,IAAI,MACR,iLAEF;GAEF,IAAI,YAAY;IAEd,MAAM,iBAAiB,IAAI,eAAe;IAC1C,eAAe,IAAI,QAAQ;KAAE,UAAU,MAAM;KAAQ,gBAAgB,MAAM;IAAM,CAAC;IAClF,MAAM,KAAK,wBAAwB;KACjC,YACE,aAAa,YACT,EAAE,QAAQ,WAAW,IACrB;MAAE,QAAQ;MAAY,UAAU,UAAU;KAAsC;KACtF;KACA;IACF,CAAC;GACH,OAAO;IACL,MAAM,SAAS,KAAK,sBAAsB;KACxC;KACA;KACA,GAAI,aAAa,YACb,EAAE,gBAAgB,EAAE,QAAQ,UAAU,sCAAsC,EAAE,IAC9E,CAAC;IACP,CAAC;IACD,IAAI,CAAC,OAAO,UAAU,MAAM,IAAI,MAAM,gCAAgC,OAAO,OAAO,GAAG;GACzF;GAEA,KAAK,cAAc,OAAO;IACxB,OAAO,MAAM;IACb,SAAS,MAAM;IACf,WAAW;IACX,GAAI,MAAM,eAAe,EAAE,cAAc,MAAM,aAAa,IAAI,CAAC;IACjE,QAAQ,aAAa,YAAY,yBAAyB;IAC1D,kBAAkB,MAAM;IACxB,SAAS,CACP;KAAE,MAAM;KAAW,IAAI;IAAU,GACjC,GAAI,UAAU,CAAC;KAAE,MAAM;KAAsB,IAAI,QAAQ;IAAW,CAAC,IAAI,CAAC,CAC5E;IACA,UAAU;KAAE;KAAY;KAAW;KAAU,OAAO;IAAgB;GACtE,CAAC;GACD,OAAO;IAAE,UAAU;IAAU;IAAW;GAAW;EACrD;CACF,CAEuC,EAAE;AAC3C"}
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export interface CreateFactoryToolsOptions {
|
|
|
22
22
|
* Worker and side sessions only answer messages. User sessions get every tool
|
|
23
23
|
* on every turn. Turns nobody signed in started (notification wakes, webhooks,
|
|
24
24
|
* dispatcher notices) carry text other people wrote, so each tool limits what
|
|
25
|
-
* it does on them itself: approvals, proposals
|
|
25
|
+
* it does on them itself: approvals, proposals and muting
|
|
26
26
|
* side sessions need a person, moves run as an agent, model switches reach
|
|
27
27
|
* only this session and its side sessions, and starts are side sessions only.
|
|
28
28
|
*/
|
package/dist/tools/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { resolveFactoryToolScope } from "./scope.js";
|
|
|
15
15
|
* Worker and side sessions only answer messages. User sessions get every tool
|
|
16
16
|
* on every turn. Turns nobody signed in started (notification wakes, webhooks,
|
|
17
17
|
* dispatcher notices) carry text other people wrote, so each tool limits what
|
|
18
|
-
* it does on them itself: approvals, proposals
|
|
18
|
+
* it does on them itself: approvals, proposals and muting
|
|
19
19
|
* side sessions need a person, moves run as an agent, model switches reach
|
|
20
20
|
* only this session and its side sessions, and starts are side sessions only.
|
|
21
21
|
*/
|
package/dist/tools/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals and muting\n * side sessions need a person, moves run as an agent, model switches reach\n * only this session and its side sessions, and starts are side sessions only.\n */\nexport function createFactoryTools({ scope, deps }: CreateFactoryToolsOptions): IntegrationTools {\n const messagingTools = createFactoryMessagingTools(scope, deps);\n if (scope.kind !== 'user') return messagingTools;\n return {\n ...createFactoryReadTools(scope, deps),\n ...messagingTools,\n ...createFactoryWorkItemTools(scope, deps),\n ...createFactorySessionTools(scope, deps),\n ...createFactoryApprovalTools(scope, deps),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,mBAAmB,EAAE,OAAO,QAAqD;CAC/F,MAAM,iBAAiB,4BAA4B,OAAO,IAAI;CAC9D,IAAI,MAAM,SAAS,QAAQ,OAAO;CAClC,OAAO;EACL,GAAG,uBAAuB,OAAO,IAAI;EACrC,GAAG;EACH,GAAG,2BAA2B,OAAO,IAAI;EACzC,GAAG,0BAA0B,OAAO,IAAI;EACxC,GAAG,2BAA2B,OAAO,IAAI;CAC3C;AACF"}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import type { NotificationsStorage } from '@mastra/core/notifications';
|
|
7
7
|
import type { IntegrationTools } from '../integrations/base.js';
|
|
8
8
|
import type { SourceControlSessionLookup } from '../session/factory-session.js';
|
|
9
|
+
import type { LiveSessions } from '../session/live-sessions.js';
|
|
9
10
|
import type { AuditRecorder } from '../storage/domains/audit/domain.js';
|
|
10
11
|
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
11
12
|
import type { FactoryDeliveryController } from './deliver.js';
|
|
@@ -23,6 +24,8 @@ export interface FactoryMessagingToolDependencies {
|
|
|
23
24
|
auditRecorder: AuditRecorder;
|
|
24
25
|
/** The live controller and notifications store; resolved per call because they exist only once the mount is up. */
|
|
25
26
|
messaging: () => Promise<FactoryMessaging | null>;
|
|
27
|
+
/** Which live sessions are parked on a tool prompt; absent before the mount is up. */
|
|
28
|
+
liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;
|
|
26
29
|
}
|
|
27
30
|
export declare function createFactoryMessagingTools(scope: FactoryToolScope, deps: FactoryMessagingToolDependencies): IntegrationTools;
|
|
28
31
|
//# sourceMappingURL=messaging-tools.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messaging-tools.d.ts","sourceRoot":"","sources":["../../src/tools/messaging-tools.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAGV,oBAAoB,EAErB,MAAM,4BAA4B,CAAC;AAIpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAExE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAM9E,OAAO,KAAK,EAAE,yBAAyB,EAAyB,MAAM,cAAc,CAAC;AAIrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAGnD,gFAAgF;AAChF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,qBAAqB,QAAiB,CAAC;AAyCpD,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,yBAAyB,CAAC;IACtC,aAAa,EAAE,IAAI,CAAC,oBAAoB,EAAE,mBAAmB,GAAG,iBAAiB,CAAC,CAAC;CACpF;AAED,MAAM,WAAW,gCAAgC;IAC/C,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,GAA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,IAAI,CACb,gBAAgB,EACd,gCAAgC,GAChC,eAAe,GACf,yBAAyB,GACzB,0BAA0B,GAC1B,iBAAiB,GACjB,yBAAyB,CAC5B,CAAC;IACF,aAAa,EAAE,aAAa,CAAC;IAC7B,mHAAmH;IACnH,SAAS,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC;IAClD,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,SAAS,CAAC;CAC5E;AAgBD,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,gCAAgC,GACrC,gBAAgB,CAqhBlB"}
|
|
@@ -3,8 +3,8 @@ import { workItemNumber } from "./read-tools.js";
|
|
|
3
3
|
import { reportNotification, workItemReportAttributes, workItemReportRecipients } from "./reports.js";
|
|
4
4
|
import { requirePerson } from "./scope.js";
|
|
5
5
|
import { listSideSessions, sessionModel } from "./side-sessions.js";
|
|
6
|
-
import { z } from "zod";
|
|
7
6
|
import { createTool } from "@mastra/core/tools";
|
|
7
|
+
import { z } from "zod";
|
|
8
8
|
// src/tools/messaging-tools.ts
|
|
9
9
|
/** Messages plus replies, per sender session, per target thread, per window. */
|
|
10
10
|
const SIGNAL_RATE_LIMIT = 10;
|
|
@@ -459,6 +459,7 @@ function createFactoryMessagingTools(scope, deps) {
|
|
|
459
459
|
workItems: deps.workItems,
|
|
460
460
|
notifications: messaging?.notifications ?? null,
|
|
461
461
|
isRunning: async (sessionId) => (await messaging?.controller.getSession(sessionId))?.stream.isActive() ?? false,
|
|
462
|
+
isParked: (sessionId) => deps.liveSessions?.()?.parked(sessionId) !== void 0,
|
|
462
463
|
model: messaging ? (sessionId) => sessionModel(messaging.controller, deps.sessions, deps.workItems, sessionId) : void 0
|
|
463
464
|
}, scope)).filter((row) => (!state || row.state === state) && (muted === void 0 || row.mutedAt !== null === muted)) };
|
|
464
465
|
}
|