@mastra/factory 0.29.0-alpha.3 → 0.29.0-alpha.5
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 +123 -64
- package/dist/boards/board-events.d.ts +89 -9
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +176 -13
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +14 -1
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/busy-card.d.ts +11 -0
- package/dist/boards/busy-card.d.ts.map +1 -0
- package/dist/boards/busy-card.js +15 -0
- package/dist/boards/busy-card.js.map +1 -0
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +18 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/index.d.ts +2 -1
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +3 -2
- package/dist/boards/intake-dry-run.d.ts +109 -0
- package/dist/boards/intake-dry-run.d.ts.map +1 -0
- package/dist/boards/intake-dry-run.js +158 -0
- package/dist/boards/intake-dry-run.js.map +1 -0
- package/dist/boards/intake-lookup.d.ts +32 -0
- package/dist/boards/intake-lookup.d.ts.map +1 -0
- package/dist/boards/intake-lookup.js +12 -0
- package/dist/boards/intake-lookup.js.map +1 -0
- package/dist/boards/intake-order.d.ts +32 -0
- package/dist/boards/intake-order.d.ts.map +1 -0
- package/dist/boards/intake-order.js +60 -0
- package/dist/boards/intake-order.js.map +1 -0
- package/dist/boards/intake-routing.d.ts +246 -35
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +437 -52
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/reroute.d.ts +7 -3
- package/dist/boards/reroute.d.ts.map +1 -1
- package/dist/boards/reroute.js +21 -4
- package/dist/boards/reroute.js.map +1 -1
- package/dist/boards/semantics.d.ts +8 -28
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +7 -39
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-routes.d.ts +31 -11
- package/dist/boards/work-routes.d.ts.map +1 -1
- package/dist/boards/work-routes.js +104 -20
- package/dist/boards/work-routes.js.map +1 -1
- package/dist/factory.d.ts +27 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +32 -18
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -2
- package/dist/integrations/base.d.ts +9 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/dependabot/rules.d.ts.map +1 -1
- package/dist/integrations/dependabot/rules.js +2 -6
- package/dist/integrations/dependabot/rules.js.map +1 -1
- package/dist/integrations/github/commits.d.ts +0 -21
- package/dist/integrations/github/commits.d.ts.map +1 -1
- package/dist/integrations/github/commits.js +1 -24
- package/dist/integrations/github/commits.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts +22 -1
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +23 -5
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/intake-lookup.d.ts +16 -0
- package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/github/intake-lookup.js +76 -0
- package/dist/integrations/github/intake-lookup.js.map +1 -0
- package/dist/integrations/github/integration.d.ts +20 -6
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +23 -12
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/review-status-reporter.js +1 -1
- package/dist/integrations/github/routes.d.ts +1 -11
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +20 -517
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +12 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +275 -38
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +30 -4
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +19 -3
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/discovery.d.ts +1 -1
- package/dist/integrations/gitlab/discovery.js +1 -1
- package/dist/integrations/gitlab/discovery.js.map +1 -1
- package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
- package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/gitlab/intake-lookup.js +85 -0
- package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
- package/dist/integrations/gitlab/integration.d.ts +5 -0
- package/dist/integrations/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/gitlab/integration.js +21 -2
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts +0 -2
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +49 -165
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +20 -0
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +128 -19
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +5 -5
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +3 -59
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +15 -9
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts +2 -2
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +0 -68
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +13 -7
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +2 -2
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +0 -83
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +14 -7
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +9 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +6 -6
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +23 -6
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts +2 -2
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +0 -69
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/integrations/pull-request-head.d.ts +1 -1
- package/dist/integrations/pull-request-head.d.ts.map +1 -1
- package/dist/integrations/pull-request-head.js +5 -0
- package/dist/integrations/pull-request-head.js.map +1 -1
- package/dist/integrations/vanta/rules.d.ts.map +1 -1
- package/dist/integrations/vanta/rules.js +2 -6
- package/dist/integrations/vanta/rules.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
- package/dist/routes/automation-runs.d.ts +0 -2
- package/dist/routes/automation-runs.d.ts.map +1 -1
- package/dist/routes/automation-runs.js +2 -6
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +8 -1
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +33 -7
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/config.d.ts +6 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +5 -2
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +1258 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +588 -17
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/fs.d.ts +10 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +184 -11
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake-check.d.ts +92 -0
- package/dist/routes/intake-check.d.ts.map +1 -0
- package/dist/routes/intake-check.js +322 -0
- package/dist/routes/intake-check.js.map +1 -0
- package/dist/routes/intake-routes.d.ts +10 -2
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +292 -11
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/mastra-gateway.d.ts.map +1 -1
- package/dist/routes/mastra-gateway.js +3 -2
- package/dist/routes/mastra-gateway.js.map +1 -1
- package/dist/routes/project-sessions.d.ts +49 -0
- package/dist/routes/project-sessions.d.ts.map +1 -0
- package/dist/routes/project-sessions.js +93 -0
- package/dist/routes/project-sessions.js.map +1 -0
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +4 -17
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/run-queue.d.ts +6 -6
- package/dist/routes/run-queue.d.ts.map +1 -1
- package/dist/routes/run-queue.js +28 -8
- package/dist/routes/run-queue.js.map +1 -1
- package/dist/routes/session-rows.d.ts +30 -0
- package/dist/routes/session-rows.d.ts.map +1 -0
- package/dist/routes/session-rows.js +98 -0
- package/dist/routes/session-rows.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +4 -8
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +8 -106
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +13 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +25 -38
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-starters.d.ts +1 -0
- package/dist/routes/work-item-starters.d.ts.map +1 -1
- package/dist/routes/work-item-starters.js +14 -2
- package/dist/routes/work-item-starters.js.map +1 -1
- package/dist/routes/work-items.d.ts +13 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +87 -34
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatch-errors.js +1 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +39 -7
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +362 -127
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +69 -1
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +151 -5
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +1 -6
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/review-source-tool.js +1 -1
- package/dist/rules/rule-group.d.ts +18 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +52 -8
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/run-bearing.d.ts +8 -0
- package/dist/rules/run-bearing.d.ts.map +1 -0
- package/dist/rules/run-bearing.js +11 -0
- package/dist/rules/run-bearing.js.map +1 -0
- package/dist/rules/start-coordinator.d.ts +2 -3
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +27 -35
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +2 -1
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +16 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +34 -12
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +18 -5
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +2 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/update-fold.d.ts +32 -0
- package/dist/rules/update-fold.d.ts.map +1 -0
- package/dist/rules/update-fold.js +60 -0
- package/dist/rules/update-fold.js.map +1 -0
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +54 -6
- package/dist/rules/validation.js.map +1 -1
- package/dist/session/resource-migration.d.ts.map +1 -1
- package/dist/session/resource-migration.js +2 -3
- package/dist/session/resource-migration.js.map +1 -1
- package/dist/session/run-audit.d.ts +9 -0
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js +9 -1
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +26 -2
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +60 -10
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/session-row-query.d.ts +25 -0
- package/dist/session/session-row-query.d.ts.map +1 -0
- package/dist/session/session-row-query.js +47 -0
- package/dist/session/session-row-query.js.map +1 -0
- package/dist/session/session-row-status.d.ts +16 -0
- package/dist/session/session-row-status.d.ts.map +1 -0
- package/dist/session/session-row-status.js +14 -0
- package/dist/session/session-row-status.js.map +1 -0
- package/dist/session/session-row-view.d.ts +14 -0
- package/dist/session/session-row-view.d.ts.map +1 -0
- package/dist/session/session-row-view.js +125 -0
- package/dist/session/session-row-view.js.map +1 -0
- package/dist/session/session-rows.d.ts +46 -0
- package/dist/session/session-rows.d.ts.map +1 -0
- package/dist/session/session-rows.js +232 -0
- package/dist/session/session-rows.js.map +1 -0
- package/dist/session/session-threads.d.ts.map +1 -1
- package/dist/session/session-threads.js +1 -0
- package/dist/session/session-threads.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +14 -7
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +10 -2
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/work-item-repository.d.ts +44 -0
- package/dist/session/work-item-repository.d.ts.map +1 -1
- package/dist/session/work-item-repository.js +80 -1
- package/dist/session/work-item-repository.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts.map +1 -1
- package/dist/session/work-item-state-processor.js +44 -8
- package/dist/session/work-item-state-processor.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +2 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +3 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +162 -14
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +415 -41
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts +6 -0
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +93 -3
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +11 -10
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +30 -65
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.d.ts +0 -2
- package/dist/storage/domains/integrations/base.d.ts.map +1 -1
- package/dist/storage/domains/integrations/base.js +0 -6
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +19 -22
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +0 -10
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +6 -21
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +1 -6
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +49 -53
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +152 -156
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +3 -2
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +4 -2
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +12 -3
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/storage/legacy-collections.d.ts +9 -0
- package/dist/storage/legacy-collections.d.ts.map +1 -0
- package/dist/storage/legacy-collections.js +17 -0
- package/dist/storage/legacy-collections.js.map +1 -0
- package/dist/storage/probed-list.d.ts +11 -0
- package/dist/storage/probed-list.d.ts.map +1 -0
- package/dist/storage/probed-list.js +52 -0
- package/dist/storage/probed-list.js.map +1 -0
- package/dist/tools/audit-events-tool.d.ts +2 -2
- package/dist/tools/read-tools.d.ts +0 -3
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +4 -42
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +5 -9
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +3 -0
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +8 -4
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +4 -0
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +7 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-context-sessions.d.ts +50 -0
- package/dist/work-items/card-context-sessions.d.ts.map +1 -0
- package/dist/work-items/card-context-sessions.js +84 -0
- package/dist/work-items/card-context-sessions.js.map +1 -0
- package/dist/work-items/change-requests.d.ts +87 -0
- package/dist/work-items/change-requests.d.ts.map +1 -0
- package/dist/work-items/change-requests.js +134 -0
- package/dist/work-items/change-requests.js.map +1 -0
- package/dist/work-items/create-work-item.d.ts +7 -2
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +44 -13
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/list-related-cards.d.ts.map +1 -1
- package/dist/work-items/list-related-cards.js +1 -1
- package/dist/work-items/list-related-cards.js.map +1 -1
- package/dist/work-items/providers/github.d.ts.map +1 -1
- package/dist/work-items/providers/github.js +1 -0
- package/dist/work-items/providers/github.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +1 -3
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +2 -2
- package/factory-skills/factory-build/SKILL.md +1 -1
- package/factory-skills/factory-plan/SKILL.md +5 -3
- package/factory-skills/factory-self-review/SKILL.md +2 -0
- package/factory-skills/factory-triage/SKILL.md +1 -1
- package/package.json +10 -10
- package/dist/session/filesystem-capture.d.ts +0 -50
- package/dist/session/filesystem-capture.d.ts.map +0 -1
- package/dist/session/filesystem-capture.js +0 -229
- package/dist/session/filesystem-capture.js.map +0 -1
- package/dist/storage/domains/filesystem/base.d.ts +0 -30
- package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
- package/dist/storage/domains/filesystem/base.js +0 -78
- package/dist/storage/domains/filesystem/base.js.map +0 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { BoardEventFacts } from '../boards/board-events.js';
|
|
2
|
+
import type { FactoryDeferredDecisionRecord } from '../storage/domains/work-items/base.js';
|
|
3
|
+
/** Statuses of an update still waiting to act, or given way to a newer one: their changes carry forward. */
|
|
4
|
+
export declare const FOLDABLE_UPDATE_STATUSES: ReadonlySet<string>;
|
|
5
|
+
type UpdateRecord = Pick<FactoryDeferredDecisionRecord, 'id' | 'status' | 'createdAt' | 'decision' | 'idempotencyKey'>;
|
|
6
|
+
type UpdateDecision = {
|
|
7
|
+
event: BoardEventFacts;
|
|
8
|
+
fromCardSession?: true;
|
|
9
|
+
};
|
|
10
|
+
/** The transition ingress a card-move decision commits its move under. */
|
|
11
|
+
export declare function eventRouteIngress(idempotencyKey: string): string;
|
|
12
|
+
/** Whether stored decision `stored` folds with update `decision`: same event, same pull request, same session origin. */
|
|
13
|
+
export declare function foldsWith(stored: unknown, decision: UpdateDecision): boolean;
|
|
14
|
+
/** A card's update decisions that fold together with `decision` ({@link foldsWith}), oldest first. */
|
|
15
|
+
export declare function updateGroup<T extends UpdateRecord>(records: readonly T[], decision: UpdateDecision): T[];
|
|
16
|
+
/** Whether a newer update of the group, not given up on, carries update `id`'s change. Reads no storage. */
|
|
17
|
+
export declare function updateSuperseded(group: readonly Pick<UpdateRecord, 'id' | 'status'>[], id: string): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* How the dispatcher folds update `id` of its group: `superseded` when a newer update not given up
|
|
20
|
+
* on carries this one's change (it folded it, or will), and then nothing else is read; `since` the earlier updates after the last
|
|
21
|
+
* one that moved the card; `event` the net change of the foldable ones and this one, undefined when
|
|
22
|
+
* it nets out to nothing. The group last moved the card at the newest update that succeeded, or
|
|
23
|
+
* whose move committed (`moveCommitted`) even though its decision never finished: its change is
|
|
24
|
+
* already applied.
|
|
25
|
+
*/
|
|
26
|
+
export declare function foldUpdate<T extends UpdateRecord>(group: readonly T[], id: string, moveCommitted: (record: T) => Promise<boolean>): Promise<{
|
|
27
|
+
superseded: boolean;
|
|
28
|
+
since: T[];
|
|
29
|
+
event: BoardEventFacts | undefined;
|
|
30
|
+
}>;
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=update-fold.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-fold.d.ts","sourceRoot":"","sources":["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EAAE,eAAe,GAAG,SAAS,CAAA;CAAE,CAAC,CAsBlF"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { combineUpdates } from "../boards/board-events.js";
|
|
2
|
+
// src/rules/update-fold.ts
|
|
3
|
+
/** Statuses of an update still waiting to act, or given way to a newer one: their changes carry forward. */
|
|
4
|
+
const FOLDABLE_UPDATE_STATUSES = /* @__PURE__ */ new Set([
|
|
5
|
+
"pending",
|
|
6
|
+
"retry",
|
|
7
|
+
"leased",
|
|
8
|
+
"superseded"
|
|
9
|
+
]);
|
|
10
|
+
/** The transition ingress a card-move decision commits its move under. */
|
|
11
|
+
function eventRouteIngress(idempotencyKey) {
|
|
12
|
+
return `event-route:${idempotencyKey}`;
|
|
13
|
+
}
|
|
14
|
+
/** Whether stored decision `stored` folds with update `decision`: same event, same pull request, same session origin. */
|
|
15
|
+
function foldsWith(stored, decision) {
|
|
16
|
+
const candidate = stored;
|
|
17
|
+
return candidate.type === "routeEvent" && candidate.event?.type === decision.event.type && candidate.event.pullRequest === decision.event.pullRequest && candidate.fromCardSession === true === (decision.fromCardSession === true);
|
|
18
|
+
}
|
|
19
|
+
/** A card's update decisions that fold together with `decision` ({@link foldsWith}), oldest first. */
|
|
20
|
+
function updateGroup(records, decision) {
|
|
21
|
+
return records.filter((other) => foldsWith(other.decision, decision)).toSorted((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
|
|
22
|
+
}
|
|
23
|
+
/** Whether a newer update of the group, not given up on, carries update `id`'s change. Reads no storage. */
|
|
24
|
+
function updateSuperseded(group, id) {
|
|
25
|
+
const index = group.findIndex((other) => other.id === id);
|
|
26
|
+
return group.slice(index + 1).some((other) => other.status !== "failed" && other.status !== "dismissed");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* How the dispatcher folds update `id` of its group: `superseded` when a newer update not given up
|
|
30
|
+
* on carries this one's change (it folded it, or will), and then nothing else is read; `since` the earlier updates after the last
|
|
31
|
+
* one that moved the card; `event` the net change of the foldable ones and this one, undefined when
|
|
32
|
+
* it nets out to nothing. The group last moved the card at the newest update that succeeded, or
|
|
33
|
+
* whose move committed (`moveCommitted`) even though its decision never finished: its change is
|
|
34
|
+
* already applied.
|
|
35
|
+
*/
|
|
36
|
+
async function foldUpdate(group, id, moveCommitted) {
|
|
37
|
+
const index = group.findIndex((other) => other.id === id);
|
|
38
|
+
const own = group[index];
|
|
39
|
+
if (!own) throw new Error(`Update ${id} is not in its group.`);
|
|
40
|
+
if (updateSuperseded(group, id)) return {
|
|
41
|
+
superseded: true,
|
|
42
|
+
since: [],
|
|
43
|
+
event: void 0
|
|
44
|
+
};
|
|
45
|
+
const earlier = group.slice(0, index);
|
|
46
|
+
let last = earlier.findLastIndex((other) => other.status === "succeeded");
|
|
47
|
+
for (let at = earlier.length - 1; at > last; at--) if (await moveCommitted(earlier[at])) {
|
|
48
|
+
last = at;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
const since = earlier.slice(last + 1);
|
|
52
|
+
return {
|
|
53
|
+
superseded: false,
|
|
54
|
+
since,
|
|
55
|
+
event: combineUpdates([...since.filter((other) => FOLDABLE_UPDATE_STATUSES.has(other.status)).map((other) => other.decision.event), own.decision.event])
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export { FOLDABLE_UPDATE_STATUSES, eventRouteIngress, foldUpdate, foldsWith, updateGroup, updateSuperseded };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=update-fold.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-fold.js","names":[],"sources":["../../src/rules/update-fold.ts"],"sourcesContent":["import { combineUpdates } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { FactoryDeferredDecisionRecord } from '../storage/domains/work-items/base.js';\n\n/** Statuses of an update still waiting to act, or given way to a newer one: their changes carry forward. */\nexport const FOLDABLE_UPDATE_STATUSES: ReadonlySet<string> = new Set(['pending', 'retry', 'leased', 'superseded']);\n\ntype UpdateRecord = Pick<FactoryDeferredDecisionRecord, 'id' | 'status' | 'createdAt' | 'decision' | 'idempotencyKey'>;\ntype UpdateDecision = { event: BoardEventFacts; fromCardSession?: true };\n\n/** The transition ingress a card-move decision commits its move under. */\nexport function eventRouteIngress(idempotencyKey: string): string {\n return `event-route:${idempotencyKey}`;\n}\n\n/** Whether stored decision `stored` folds with update `decision`: same event, same pull request, same session origin. */\nexport function foldsWith(stored: unknown, decision: UpdateDecision): boolean {\n const candidate = stored as { type?: unknown; event?: BoardEventFacts; fromCardSession?: unknown };\n return (\n candidate.type === 'routeEvent' &&\n candidate.event?.type === decision.event.type &&\n candidate.event.pullRequest === decision.event.pullRequest &&\n (candidate.fromCardSession === true) === (decision.fromCardSession === true)\n );\n}\n\n/** A card's update decisions that fold together with `decision` ({@link foldsWith}), oldest first. */\nexport function updateGroup<T extends UpdateRecord>(records: readonly T[], decision: UpdateDecision): T[] {\n return records\n .filter(other => foldsWith(other.decision, decision))\n .toSorted((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));\n}\n\n/** Whether a newer update of the group, not given up on, carries update `id`'s change. Reads no storage. */\nexport function updateSuperseded(group: readonly Pick<UpdateRecord, 'id' | 'status'>[], id: string): boolean {\n const index = group.findIndex(other => other.id === id);\n return group.slice(index + 1).some(other => other.status !== 'failed' && other.status !== 'dismissed');\n}\n\n/**\n * How the dispatcher folds update `id` of its group: `superseded` when a newer update not given up\n * on carries this one's change (it folded it, or will), and then nothing else is read; `since` the earlier updates after the last\n * one that moved the card; `event` the net change of the foldable ones and this one, undefined when\n * it nets out to nothing. The group last moved the card at the newest update that succeeded, or\n * whose move committed (`moveCommitted`) even though its decision never finished: its change is\n * already applied.\n */\nexport async function foldUpdate<T extends UpdateRecord>(\n group: readonly T[],\n id: string,\n moveCommitted: (record: T) => Promise<boolean>,\n): Promise<{ superseded: boolean; since: T[]; event: BoardEventFacts | undefined }> {\n const index = group.findIndex(other => other.id === id);\n const own = group[index];\n if (!own) throw new Error(`Update ${id} is not in its group.`);\n // A newer update carries this one's change, so nothing here acts: skip the reads below.\n if (updateSuperseded(group, id)) return { superseded: true, since: [], event: undefined };\n const earlier = group.slice(0, index);\n let last = earlier.findLastIndex(other => other.status === 'succeeded');\n for (let at = earlier.length - 1; at > last; at--) {\n if (await moveCommitted(earlier[at]!)) {\n last = at;\n break;\n }\n }\n const since = earlier.slice(last + 1);\n const event = combineUpdates([\n ...since\n .filter(other => FOLDABLE_UPDATE_STATUSES.has(other.status))\n .map(other => (other.decision as unknown as UpdateDecision).event),\n (own.decision as unknown as UpdateDecision).event,\n ]);\n return { superseded: false, since, event };\n}\n"],"mappings":";;;AAKA,MAAa,2CAAgD,IAAI,IAAI;CAAC;CAAW;CAAS;CAAU;AAAY,CAAC;;AAMjH,SAAgB,kBAAkB,gBAAgC;CAChE,OAAO,eAAe;AACxB;;AAGA,SAAgB,UAAU,QAAiB,UAAmC;CAC5E,MAAM,YAAY;CAClB,OACE,UAAU,SAAS,gBACnB,UAAU,OAAO,SAAS,SAAS,MAAM,QACzC,UAAU,MAAM,gBAAgB,SAAS,MAAM,eAC9C,UAAU,oBAAoB,UAAW,SAAS,oBAAoB;AAE3E;;AAGA,SAAgB,YAAoC,SAAuB,UAA+B;CACxG,OAAO,QACJ,QAAO,UAAS,UAAU,MAAM,UAAU,QAAQ,CAAC,CAAC,CACpD,UAAU,GAAG,MAAM,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,KAAK,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AACjG;;AAGA,SAAgB,iBAAiB,OAAuD,IAAqB;CAC3G,MAAM,QAAQ,MAAM,WAAU,UAAS,MAAM,OAAO,EAAE;CACtD,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,CAAC,MAAK,UAAS,MAAM,WAAW,YAAY,MAAM,WAAW,WAAW;AACvG;;;;;;;;;AAUA,eAAsB,WACpB,OACA,IACA,eAC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B,CAAC;AAElE,mGAAmG;AACnG,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEjE;AAQD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,EAAE,WAAW,SAAI,GAAG,mBAAmB,CA2ShG;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,EAAE,WAAW,SAAI,GAAG,qBAAqB,EAAE,CAiBjH"}
|
package/dist/rules/validation.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from "../boards/board-events.js";
|
|
1
|
+
import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS, isUpdateEvent } from "../boards/board-events.js";
|
|
2
2
|
// src/rules/validation.ts
|
|
3
3
|
const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;
|
|
4
4
|
const MAX_VERSION_LENGTH = 128;
|
|
@@ -80,12 +80,55 @@ function boardIdentifier(value, label) {
|
|
|
80
80
|
}
|
|
81
81
|
function boardEvent(value, label) {
|
|
82
82
|
if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);
|
|
83
|
-
assertExactKeys(value, [
|
|
83
|
+
assertExactKeys(value, [
|
|
84
|
+
"type",
|
|
85
|
+
"reason",
|
|
86
|
+
"labels",
|
|
87
|
+
"assignees",
|
|
88
|
+
"pullRequest",
|
|
89
|
+
"pullRequestTrusted",
|
|
90
|
+
"closedIssue"
|
|
91
|
+
], `${label} event`);
|
|
84
92
|
const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);
|
|
85
93
|
const reason = value.reason === void 0 ? void 0 : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);
|
|
94
|
+
if ((value.labels !== void 0 || value.assignees !== void 0) && !isUpdateEvent(type)) throw new FactoryRuleValidationError(`${label} event only carries changes on an update.`);
|
|
95
|
+
const labels = itemChange(value.labels, `${label} event labels`);
|
|
96
|
+
const assignees = itemChange(value.assignees, `${label} event assignees`);
|
|
97
|
+
if (value.pullRequestTrusted !== void 0 && typeof value.pullRequestTrusted !== "boolean") throw new FactoryRuleValidationError(`${label} event pullRequestTrusted must be a boolean.`);
|
|
98
|
+
if (value.pullRequest !== void 0 && (typeof value.pullRequest !== "string" || value.pullRequest.length === 0)) throw new FactoryRuleValidationError(`${label} event pullRequest must be a non-empty string.`);
|
|
86
99
|
return {
|
|
87
100
|
type,
|
|
88
|
-
...reason ? { reason } : {}
|
|
101
|
+
...reason ? { reason } : {},
|
|
102
|
+
...labels ? { labels } : {},
|
|
103
|
+
...assignees ? { assignees } : {},
|
|
104
|
+
...typeof value.pullRequest === "string" ? { pullRequest: value.pullRequest } : {},
|
|
105
|
+
...typeof value.pullRequestTrusted === "boolean" ? { pullRequestTrusted: value.pullRequestTrusted } : {},
|
|
106
|
+
...value.closedIssue !== void 0 ? { closedIssue: closedIssueFacts(value.closedIssue, label) } : {}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const MAX_CHANGED_NAMES = 100;
|
|
110
|
+
const MAX_CHANGED_NAME_LENGTH = 500;
|
|
111
|
+
function itemChange(value, label) {
|
|
112
|
+
if (value === void 0) return void 0;
|
|
113
|
+
if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} must be an object.`);
|
|
114
|
+
assertExactKeys(value, ["added", "removed"], label);
|
|
115
|
+
const names = (list, side) => {
|
|
116
|
+
if (!Array.isArray(list) || list.length > MAX_CHANGED_NAMES) throw new FactoryRuleValidationError(`${label} ${side} must be a list of at most ${MAX_CHANGED_NAMES} names.`);
|
|
117
|
+
return list.map((name) => boundedString(name, `${label} ${side}`, MAX_CHANGED_NAME_LENGTH));
|
|
118
|
+
};
|
|
119
|
+
return {
|
|
120
|
+
added: names(value.added, "added"),
|
|
121
|
+
removed: names(value.removed, "removed")
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function closedIssueFacts(value, label) {
|
|
125
|
+
if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event closedIssue must be an object.`);
|
|
126
|
+
assertExactKeys(value, ["phase", "hasPullRequest"], `${label} event closedIssue`);
|
|
127
|
+
if (value.phase !== null && !isBoardIdentifier(value.phase)) throw new FactoryRuleValidationError(`${label} event closedIssue.phase is invalid.`);
|
|
128
|
+
if (typeof value.hasPullRequest !== "boolean") throw new FactoryRuleValidationError(`${label} event closedIssue.hasPullRequest must be a boolean.`);
|
|
129
|
+
return {
|
|
130
|
+
phase: value.phase,
|
|
131
|
+
hasPullRequest: value.hasPullRequest
|
|
89
132
|
};
|
|
90
133
|
}
|
|
91
134
|
function linkedItemReference(value, field) {
|
|
@@ -214,17 +257,22 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
214
257
|
...value.event !== void 0 ? { event: boardEvent(value.event, "Factory transition") } : {}
|
|
215
258
|
};
|
|
216
259
|
}
|
|
217
|
-
case "routeEvent":
|
|
260
|
+
case "routeEvent": {
|
|
218
261
|
assertExactKeys(value, [
|
|
219
262
|
"type",
|
|
220
263
|
"idempotencyKey",
|
|
221
|
-
"event"
|
|
264
|
+
"event",
|
|
265
|
+
"fromCardSession"
|
|
222
266
|
], "Factory routeEvent decision");
|
|
267
|
+
const event = boardEvent(value.event, "Factory routeEvent");
|
|
268
|
+
if (value.fromCardSession !== void 0 && (value.fromCardSession !== true || !isUpdateEvent(event.type))) throw new FactoryRuleValidationError("Factory routeEvent fromCardSession is only true, on an update.");
|
|
223
269
|
return {
|
|
224
270
|
type,
|
|
225
271
|
...commonCommitFields(value),
|
|
226
|
-
event
|
|
272
|
+
event,
|
|
273
|
+
...value.fromCardSession ? { fromCardSession: true } : {}
|
|
227
274
|
};
|
|
275
|
+
}
|
|
228
276
|
case "signalActivity": {
|
|
229
277
|
assertExactKeys(value, [
|
|
230
278
|
"type",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_DESCRIPTION_LENGTH = 8000;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'github-dependabot-alert',\n 'vanta-vulnerability',\n 'detail-finding',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(value, ['type', 'reason'], `${label} event`);\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n return { type, ...(reason ? { reason } : {}) };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event'], 'Factory routeEvent decision');\n return { type, ...commonCommitFields(value), event: boardEvent(value.event, 'Factory routeEvent') };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'description',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n ...(value.description === undefined\n ? {}\n : {\n description: boundedString(\n value.description,\n 'Factory linked work item description',\n MAX_DESCRIPTION_LENGTH,\n ),\n }),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,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zG,iBAAiB,cAAc,MAAM,iBAAiB,mCAAmC,gBAAgB;GAC3G;EAEF,SACE,MAAM,IAAI,2BAA2B,4CAA4C;CACrF;AACF;AAEA,SAAgB,6BAA6B,QAA4B,cAAc,GAA4B;CACjH,IAAI,OAAO,SAAS,0BAClB,MAAM,IAAI,2BAA2B,2CAA2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, isUpdateEvent, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts, ItemChange } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_DESCRIPTION_LENGTH = 8000;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'github-dependabot-alert',\n 'vanta-vulnerability',\n 'detail-finding',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(\n value,\n ['type', 'reason', 'labels', 'assignees', 'pullRequest', 'pullRequestTrusted', 'closedIssue'],\n `${label} event`,\n );\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n if ((value.labels !== undefined || value.assignees !== undefined) && !isUpdateEvent(type)) {\n throw new FactoryRuleValidationError(`${label} event only carries changes on an update.`);\n }\n const labels = itemChange(value.labels, `${label} event labels`);\n const assignees = itemChange(value.assignees, `${label} event assignees`);\n if (value.pullRequestTrusted !== undefined && typeof value.pullRequestTrusted !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event pullRequestTrusted must be a boolean.`);\n }\n if (value.pullRequest !== undefined && (typeof value.pullRequest !== 'string' || value.pullRequest.length === 0)) {\n throw new FactoryRuleValidationError(`${label} event pullRequest must be a non-empty string.`);\n }\n return {\n type,\n ...(reason ? { reason } : {}),\n ...(labels ? { labels } : {}),\n ...(assignees ? { assignees } : {}),\n ...(typeof value.pullRequest === 'string' ? { pullRequest: value.pullRequest } : {}),\n ...(typeof value.pullRequestTrusted === 'boolean' ? { pullRequestTrusted: value.pullRequestTrusted } : {}),\n ...(value.closedIssue !== undefined ? { closedIssue: closedIssueFacts(value.closedIssue, label) } : {}),\n };\n}\n\nconst MAX_CHANGED_NAMES = 100;\nconst MAX_CHANGED_NAME_LENGTH = 500;\n\nfunction itemChange(value: unknown, label: string): ItemChange | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n assertExactKeys(value, ['added', 'removed'], label);\n const names = (list: unknown, side: string) => {\n if (!Array.isArray(list) || list.length > MAX_CHANGED_NAMES) {\n throw new FactoryRuleValidationError(`${label} ${side} must be a list of at most ${MAX_CHANGED_NAMES} names.`);\n }\n return list.map(name => boundedString(name, `${label} ${side}`, MAX_CHANGED_NAME_LENGTH));\n };\n return { added: names(value.added, 'added'), removed: names(value.removed, 'removed') };\n}\n\nfunction closedIssueFacts(value: unknown, label: string): NonNullable<BoardEventFacts['closedIssue']> {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event closedIssue must be an object.`);\n assertExactKeys(value, ['phase', 'hasPullRequest'], `${label} event closedIssue`);\n if (value.phase !== null && !isBoardIdentifier(value.phase)) {\n throw new FactoryRuleValidationError(`${label} event closedIssue.phase is invalid.`);\n }\n if (typeof value.hasPullRequest !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event closedIssue.hasPullRequest must be a boolean.`);\n }\n return { phase: value.phase, hasPullRequest: value.hasPullRequest };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event', 'fromCardSession'], 'Factory routeEvent decision');\n const event = boardEvent(value.event, 'Factory routeEvent');\n if (value.fromCardSession !== undefined && (value.fromCardSession !== true || !isUpdateEvent(event.type))) {\n throw new FactoryRuleValidationError('Factory routeEvent fromCardSession is only true, on an update.');\n }\n return { type, ...commonCommitFields(value), event, ...(value.fromCardSession ? { fromCardSession: true } : {}) };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'description',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n ...(value.description === undefined\n ? {}\n : {\n description: boundedString(\n value.description,\n 'Factory linked work item description',\n MAX_DESCRIPTION_LENGTH,\n ),\n }),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,oBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,kBAAuD;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,6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":"resource-migration.d.ts","sourceRoot":"","sources":["../../src/session/resource-migration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;
|
|
1
|
+
{"version":3,"file":"resource-migration.d.ts","sourceRoot":"","sources":["../../src/session/resource-migration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAalE,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE;QACR,qCAAqC,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;QACzE,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KACzD,CAAC;IACF,SAAS,EAAE;QACT,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,gBAAgB,GAAG,UAAU,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;QACpG,yBAAyB,CAAC,KAAK,EAAE;YAAE,SAAS,EAAE,MAAM,CAAC;YAAC,UAAU,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;KAC9F,CAAC;IACF,gGAAgG;IAChG,YAAY,CAAC,EAAE;QACb,2BAA2B,CAAC,KAAK,EAAE;YAAE,cAAc,EAAE,MAAM,CAAC;YAAC,YAAY,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AAED,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,EAAE;QACR,mCAAmC,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;QACvE,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE;YAAE,WAAW,EAAE,OAAO,CAAA;SAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KAC5F,CAAC;IACF,SAAS,EAAE,IAAI,CAAC,4BAA4B,CAAC,WAAW,CAAC,EAAE,mBAAmB,CAAC,CAAC;IAChF,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,eAAe,CAAC,CAAC;CAC9C;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CAAC,IAAI,EAAE,6BAA6B,GAAG,OAAO,CAAC,MAAM,CAAC,CAsBzG"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { externallyAuthoredWorkItem } from "../rules/types.js";
|
|
2
|
+
import "../work-item-branch.js";
|
|
2
3
|
import { sessionStampCounts } from "./session-threads.js";
|
|
3
4
|
// src/session/resource-migration.ts
|
|
4
|
-
/** Slack-started sessions live on a `slack/<thread>` branch (see `threadBranch` in the Slack integration). */
|
|
5
|
-
const SLACK_SESSION_BRANCH_PREFIX = "slack/";
|
|
6
5
|
/**
|
|
7
6
|
* Set on a thread while it moves and turned off once the move, vectors included, is done. A
|
|
8
7
|
* crash in between leaves the thread moved in storage but no longer listed under its
|
|
@@ -25,7 +24,7 @@ function sessionMemoryResource(session, boundItems) {
|
|
|
25
24
|
owner: "isolated",
|
|
26
25
|
resourceId: session.sessionId
|
|
27
26
|
};
|
|
28
|
-
const sharedWithOrg = session.visibility !== "private" && (session.originSessionId !== null || session.branch.startsWith(
|
|
27
|
+
const sharedWithOrg = session.visibility !== "private" && (session.originSessionId !== null || session.branch.startsWith("slack/"));
|
|
29
28
|
return boundItems.length > 0 || sharedWithOrg ? {
|
|
30
29
|
owner: "factory",
|
|
31
30
|
resourceId: session.factoryProjectId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-migration.js","names":[],"sources":["../../src/session/resource-migration.ts"],"sourcesContent":["import type { StorageThreadType } from '@mastra/core/memory';\nimport type { MemoryStorage } from '@mastra/core/storage';\n\nimport { externallyAuthoredWorkItem } from '../rules/types.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { sessionStampCounts } from './session-threads.js';\n\n/** Slack-started sessions live on a `slack/<thread>` branch (see `threadBranch` in the Slack integration). */\nconst SLACK_SESSION_BRANCH_PREFIX = 'slack/';\n\n/**\n * Set on a thread while it moves and turned off once the move, vectors included, is done. A\n * crash in between leaves the thread moved in storage but no longer listed under its\n * session id, so the next start finds it by this flag and its session stamp and finishes the move.\n */\nconst MOVE_PENDING_KEY = 'factoryResourceMovePending';\n/** How often a long resource migration reports how far it got. */\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nexport interface SessionResourceMigrationDeps {\n sessions: {\n listSessionsAwaitingResourceMigration(): Promise<SourceControlSession[]>;\n markResourcesMigrated(sessionId: string): Promise<void>;\n };\n workItems: {\n listRunBoundItems(sessionId: string): Promise<(Pick<Card, 'externalSource' | 'metadata'> | null)[]>;\n moveRunBindingsToResource(input: { sessionId: string; resourceId: string }): Promise<number>;\n };\n /** Absent when the integrations domain is not ready; subscriptions then stay where they are. */\n integrations?: {\n moveSubscriptionsToResource(input: { fromResourceId: string; toResourceId: string }): Promise<number>;\n };\n memory: Pick<MemoryStorage, 'listThreads' | 'patchThread' | 'getObservationalMemory' | 'supportsObservationalMemory'>;\n /**\n * Moves a thread with everything keyed by its resource, such as observation vectors. Pass the\n * sessions' `Memory`; the bare memory store only moves the thread and its messages.\n */\n threads: { updateThreadResourceId(input: { threadId: string; resourceId: string }): Promise<StorageThreadType> };\n}\n\nexport interface SessionResourceMigrationReport {\n sessions: number;\n factorySessions: number;\n userSessions: number;\n /** Runs on untrusted content; they keep their own resource. */\n isolatedSessions: number;\n /** Factory-owned sessions with no Factory to move them onto; left untouched. */\n skipped: string[];\n /** Sessions whose move threw; the next startup retries them. */\n failed: string[];\n /**\n * Moved sessions whose subscriptions couldn't move because the integrations\n * domain wasn't ready; left unmarked so a later startup moves them.\n */\n subscriptionsPending: string[];\n threads: number;\n runBindings: number;\n subscriptions: number;\n /** Moved sessions whose resource-scoped observational memory stays under their old resource. */\n resourceObservationsLeft: string[];\n}\n\n/**\n * The memory resource a session belongs to: its Factory for runs, side\n * sessions and Slack channel threads, its owner for sessions a person opened,\n * private side sessions and Slack DMs. A run on untrusted content (a pull request, or a card\n * written outside the write-access circle) keeps its own resource, like a new\n * run would; so does a run whose work item no longer loads, since nothing then\n * shows its content was trusted. `null` when a Factory-owned session has no\n * Factory recorded — guessing would merge it into the wrong resource.\n */\nexport function sessionMemoryResource(\n session: SourceControlSession,\n boundItems: (Pick<Card, 'externalSource' | 'metadata'> | null)[],\n): { owner: 'factory' | 'user' | 'isolated'; resourceId: string | null } {\n if (boundItems.some(item => item === null || untrustedWorkItem(item))) {\n return { owner: 'isolated', resourceId: session.sessionId };\n }\n // A Slack DM or private side session is its owner's, so it belongs with their own sessions.\n const sharedWithOrg =\n session.visibility !== 'private' &&\n (session.originSessionId !== null || session.branch.startsWith(SLACK_SESSION_BRANCH_PREFIX));\n const factoryOwned = boundItems.length > 0 || sharedWithOrg;\n return factoryOwned\n ? { owner: 'factory', resourceId: session.factoryProjectId }\n : { owner: 'user', resourceId: session.userId };\n}\n\nfunction untrustedWorkItem(item: Pick<Card, 'externalSource' | 'metadata'>): boolean {\n return item.externalSource?.type === 'pull-request' || externallyAuthoredWorkItem(item);\n}\n\n/**\n * Move sessions stored under the legacy `resourceId = sessionId` onto their\n * Factory or user resource. Threads keep their id (`threadId === sessionId`)\n * and get `factorySessionId` so per-session listings still find them.\n *\n * Threads move through the sessions' `Memory`, so their observation vectors\n * follow them and recall search finds their past observations under the new\n * resource. Every write only touches values still equal to the session id, so\n * a rerun is a no-op and a crash leaves a state the next run resumes from. A\n * session is marked once moved, so later starts only read sessions that are not\n * (new sessions are created marked).\n * Nothing is deleted. Thread-scoped observational memory is keyed by thread id\n * and keeps working. Resource-scoped observational memory written under\n * `resource:<sessionId>` stays under that key and is no longer read: several\n * sessions merge into one resource, and their records cannot be merged.\n */\nexport async function migrateSessionResources(\n deps: SessionResourceMigrationDeps,\n): Promise<SessionResourceMigrationReport> {\n const report: SessionResourceMigrationReport = {\n sessions: 0,\n factorySessions: 0,\n userSessions: 0,\n isolatedSessions: 0,\n skipped: [],\n failed: [],\n subscriptionsPending: [],\n threads: 0,\n runBindings: 0,\n subscriptions: 0,\n resourceObservationsLeft: [],\n };\n const sessions = await deps.sessions.listSessionsAwaitingResourceMigration();\n // This pass can take minutes against a remote database, so say what it is doing and\n // how far it got.\n if (sessions.length > 0) {\n console.info(`[factory] session resource migration: moving ${sessions.length} sessions in the background`);\n }\n let lastProgressAt = Date.now();\n\n for (const session of sessions) {\n report.sessions += 1;\n const { sessionId } = session;\n try {\n const { owner, resourceId } = sessionMemoryResource(session, await deps.workItems.listRunBoundItems(sessionId));\n if (!resourceId) {\n report.skipped.push(sessionId);\n continue;\n }\n if (owner === 'factory') report.factorySessions += 1;\n else if (owner === 'isolated') report.isolatedSessions += 1;\n else report.userSessions += 1;\n if (resourceId === sessionId) {\n await deps.sessions.markResourcesMigrated(sessionId);\n continue;\n }\n\n // Finish moves a crash interrupted after storage moved the thread.\n const { threads: interrupted } = await deps.memory.listThreads({\n filter: { resourceId, metadata: { factorySessionId: sessionId, [MOVE_PENDING_KEY]: true } },\n perPage: false,\n });\n for (const thread of interrupted) {\n if (thread.resourceId === sessionId) continue; // listed under the session id below\n await moveThread(deps, thread, thread.resourceId);\n report.threads += 1;\n }\n const { threads } = await deps.memory.listThreads({ filter: { resourceId: sessionId }, perPage: false });\n // A private session's stamps don't count under its Factory, so only its own\n // thread moves there; its other threads stay listed under its id.\n const stampsCount = sessionStampCounts(session, resourceId);\n for (const thread of threads) {\n if (!stampsCount && thread.id !== sessionId) continue;\n // Tag before moving: once moved, the thread is no longer found under the session id.\n const metadata = { ...thread.metadata, factorySessionId: sessionId, [MOVE_PENDING_KEY]: true };\n await deps.memory.patchThread({ id: thread.id, metadata });\n await moveThread(deps, { ...thread, metadata }, resourceId);\n report.threads += 1;\n }\n report.runBindings += await deps.workItems.moveRunBindingsToResource({ sessionId, resourceId });\n if (deps.integrations) {\n report.subscriptions += await deps.integrations.moveSubscriptionsToResource({\n fromResourceId: sessionId,\n toResourceId: resourceId,\n });\n }\n // Reported once, on the run that moves the session's threads.\n if (\n threads.length > 0 &&\n deps.memory.supportsObservationalMemory &&\n (await deps.memory.getObservationalMemory(null, sessionId))\n ) {\n report.resourceObservationsLeft.push(sessionId);\n console.warn(\n `[factory] session resource migration: session ${sessionId} has resource-scoped observational memory; ` +\n `it stays under resource ${sessionId} and is not carried into ${resourceId}`,\n );\n }\n if (!deps.integrations) {\n report.subscriptionsPending.push(sessionId);\n continue;\n }\n await deps.sessions.markResourcesMigrated(sessionId);\n } catch (error) {\n report.failed.push(sessionId);\n console.warn(\n `[factory] session resource migration: session ${sessionId} not moved: ${error instanceof Error ? error.message : error}`,\n );\n } finally {\n if (report.sessions < sessions.length && Date.now() - lastProgressAt >= PROGRESS_LOG_INTERVAL_MS) {\n lastProgressAt = Date.now();\n console.info(\n `[factory] session resource migration: ${report.sessions}/${sessions.length} sessions checked, ` +\n `${report.threads} threads moved`,\n );\n }\n }\n }\n\n if (\n report.threads +\n report.runBindings +\n report.subscriptions +\n report.skipped.length +\n report.failed.length +\n report.subscriptionsPending.length >\n 0\n ) {\n console.info(\n `[factory] session resource migration: ${report.threads} threads, ${report.runBindings} run bindings, ` +\n `${report.subscriptions} subscriptions moved; ${report.skipped.length} Factory sessions without a Factory skipped; ` +\n `${report.failed.length} sessions failed; ${report.subscriptionsPending.length} sessions wait for integrations ` +\n `to move their subscriptions`,\n );\n }\n return report;\n}\n\nexport interface SessionVisibilityBackfillDeps {\n sessions: {\n listSessionsAwaitingVisibilityCheck(): Promise<SourceControlSession[]>;\n markVisibilityChecked(sessionId: string, options: { makePrivate: boolean }): Promise<void>;\n };\n workItems: Pick<SessionResourceMigrationDeps['workItems'], 'listRunBoundItems'>;\n memory: Pick<MemoryStorage, 'getThreadById'>;\n}\n\n/**\n * Mark shared user sessions private when their conversation lives on their owner's resource.\n * The resource already keeps teammates out of such a session; this makes lists agree, so they\n * stop seeing a session they can't open. Sessions shared onto their Factory, runs, Slack threads\n * and side sessions are left alone. Each session is checked once: new sessions start checked,\n * and a session that throws stays unchecked so the next start retries it.\n */\nexport async function privatizeOwnerResourceSessions(deps: SessionVisibilityBackfillDeps): Promise<number> {\n let privatized = 0;\n for (const session of await deps.sessions.listSessionsAwaitingVisibilityCheck()) {\n try {\n let makePrivate = false;\n if (session.visibility !== 'private') {\n const { owner } = sessionMemoryResource(session, await deps.workItems.listRunBoundItems(session.sessionId));\n const thread = owner === 'user' ? await deps.memory.getThreadById({ threadId: session.sessionId }) : null;\n makePrivate = thread?.resourceId === session.userId;\n }\n await deps.sessions.markVisibilityChecked(session.sessionId, { makePrivate });\n if (makePrivate) privatized += 1;\n } catch (error) {\n console.warn(\n `[factory] session visibility check: session ${session.sessionId} not checked: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n if (privatized > 0) {\n console.info(`[factory] session visibility check: ${privatized} sessions on their owner's memory made private`);\n }\n return privatized;\n}\n\nasync function moveThread(\n deps: SessionResourceMigrationDeps,\n thread: StorageThreadType,\n resourceId: string,\n): Promise<void> {\n await deps.threads.updateThreadResourceId({ threadId: thread.id, resourceId });\n // Stores merge thread metadata, so the flag is switched off rather than removed.\n await deps.memory.patchThread({ id: thread.id, metadata: { ...thread.metadata, [MOVE_PENDING_KEY]: false } });\n}\n"],"mappings":";;;;AASA,MAAM,8BAA8B;;;;;;AAOpC,MAAM,mBAAmB;;AAEzB,MAAM,2BAA2B;;;;;;;;;;AAsDjC,SAAgB,sBACd,SACA,YACuE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;CACf,MAAM,KAAK,QAAQ,uBAAuB;EAAE,UAAU,OAAO;EAAI;CAAW,CAAC;CAE7E,MAAM,KAAK,OAAO,YAAY;EAAE,IAAI,OAAO;EAAI,UAAU;GAAE,GAAG,OAAO;IAAW,mBAAmB;EAAM;CAAE,CAAC;AAC9G"}
|
|
1
|
+
{"version":3,"file":"resource-migration.js","names":[],"sources":["../../src/session/resource-migration.ts"],"sourcesContent":["import type { StorageThreadType } from '@mastra/core/memory';\nimport type { MemoryStorage } from '@mastra/core/storage';\n\nimport { externallyAuthoredWorkItem } from '../rules/types.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { SLACK_SESSION_BRANCH_PREFIX } from '../work-item-branch.js';\nimport { sessionStampCounts } from './session-threads.js';\n\n/**\n * Set on a thread while it moves and turned off once the move, vectors included, is done. A\n * crash in between leaves the thread moved in storage but no longer listed under its\n * session id, so the next start finds it by this flag and its session stamp and finishes the move.\n */\nconst MOVE_PENDING_KEY = 'factoryResourceMovePending';\n/** How often a long resource migration reports how far it got. */\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nexport interface SessionResourceMigrationDeps {\n sessions: {\n listSessionsAwaitingResourceMigration(): Promise<SourceControlSession[]>;\n markResourcesMigrated(sessionId: string): Promise<void>;\n };\n workItems: {\n listRunBoundItems(sessionId: string): Promise<(Pick<Card, 'externalSource' | 'metadata'> | null)[]>;\n moveRunBindingsToResource(input: { sessionId: string; resourceId: string }): Promise<number>;\n };\n /** Absent when the integrations domain is not ready; subscriptions then stay where they are. */\n integrations?: {\n moveSubscriptionsToResource(input: { fromResourceId: string; toResourceId: string }): Promise<number>;\n };\n memory: Pick<MemoryStorage, 'listThreads' | 'patchThread' | 'getObservationalMemory' | 'supportsObservationalMemory'>;\n /**\n * Moves a thread with everything keyed by its resource, such as observation vectors. Pass the\n * sessions' `Memory`; the bare memory store only moves the thread and its messages.\n */\n threads: { updateThreadResourceId(input: { threadId: string; resourceId: string }): Promise<StorageThreadType> };\n}\n\nexport interface SessionResourceMigrationReport {\n sessions: number;\n factorySessions: number;\n userSessions: number;\n /** Runs on untrusted content; they keep their own resource. */\n isolatedSessions: number;\n /** Factory-owned sessions with no Factory to move them onto; left untouched. */\n skipped: string[];\n /** Sessions whose move threw; the next startup retries them. */\n failed: string[];\n /**\n * Moved sessions whose subscriptions couldn't move because the integrations\n * domain wasn't ready; left unmarked so a later startup moves them.\n */\n subscriptionsPending: string[];\n threads: number;\n runBindings: number;\n subscriptions: number;\n /** Moved sessions whose resource-scoped observational memory stays under their old resource. */\n resourceObservationsLeft: string[];\n}\n\n/**\n * The memory resource a session belongs to: its Factory for runs, side\n * sessions and Slack channel threads, its owner for sessions a person opened,\n * private side sessions and Slack DMs. A run on untrusted content (a pull request, or a card\n * written outside the write-access circle) keeps its own resource, like a new\n * run would; so does a run whose work item no longer loads, since nothing then\n * shows its content was trusted. `null` when a Factory-owned session has no\n * Factory recorded — guessing would merge it into the wrong resource.\n */\nexport function sessionMemoryResource(\n session: SourceControlSession,\n boundItems: (Pick<Card, 'externalSource' | 'metadata'> | null)[],\n): { owner: 'factory' | 'user' | 'isolated'; resourceId: string | null } {\n if (boundItems.some(item => item === null || untrustedWorkItem(item))) {\n return { owner: 'isolated', resourceId: session.sessionId };\n }\n // A Slack DM or private side session is its owner's, so it belongs with their own sessions.\n const sharedWithOrg =\n session.visibility !== 'private' &&\n (session.originSessionId !== null || session.branch.startsWith(SLACK_SESSION_BRANCH_PREFIX));\n const factoryOwned = boundItems.length > 0 || sharedWithOrg;\n return factoryOwned\n ? { owner: 'factory', resourceId: session.factoryProjectId }\n : { owner: 'user', resourceId: session.userId };\n}\n\nfunction untrustedWorkItem(item: Pick<Card, 'externalSource' | 'metadata'>): boolean {\n return item.externalSource?.type === 'pull-request' || externallyAuthoredWorkItem(item);\n}\n\n/**\n * Move sessions stored under the legacy `resourceId = sessionId` onto their\n * Factory or user resource. Threads keep their id (`threadId === sessionId`)\n * and get `factorySessionId` so per-session listings still find them.\n *\n * Threads move through the sessions' `Memory`, so their observation vectors\n * follow them and recall search finds their past observations under the new\n * resource. Every write only touches values still equal to the session id, so\n * a rerun is a no-op and a crash leaves a state the next run resumes from. A\n * session is marked once moved, so later starts only read sessions that are not\n * (new sessions are created marked).\n * Nothing is deleted. Thread-scoped observational memory is keyed by thread id\n * and keeps working. Resource-scoped observational memory written under\n * `resource:<sessionId>` stays under that key and is no longer read: several\n * sessions merge into one resource, and their records cannot be merged.\n */\nexport async function migrateSessionResources(\n deps: SessionResourceMigrationDeps,\n): Promise<SessionResourceMigrationReport> {\n const report: SessionResourceMigrationReport = {\n sessions: 0,\n factorySessions: 0,\n userSessions: 0,\n isolatedSessions: 0,\n skipped: [],\n failed: [],\n subscriptionsPending: [],\n threads: 0,\n runBindings: 0,\n subscriptions: 0,\n resourceObservationsLeft: [],\n };\n const sessions = await deps.sessions.listSessionsAwaitingResourceMigration();\n // This pass can take minutes against a remote database, so say what it is doing and\n // how far it got.\n if (sessions.length > 0) {\n console.info(`[factory] session resource migration: moving ${sessions.length} sessions in the background`);\n }\n let lastProgressAt = Date.now();\n\n for (const session of sessions) {\n report.sessions += 1;\n const { sessionId } = session;\n try {\n const { owner, resourceId } = sessionMemoryResource(session, await deps.workItems.listRunBoundItems(sessionId));\n if (!resourceId) {\n report.skipped.push(sessionId);\n continue;\n }\n if (owner === 'factory') report.factorySessions += 1;\n else if (owner === 'isolated') report.isolatedSessions += 1;\n else report.userSessions += 1;\n if (resourceId === sessionId) {\n await deps.sessions.markResourcesMigrated(sessionId);\n continue;\n }\n\n // Finish moves a crash interrupted after storage moved the thread.\n const { threads: interrupted } = await deps.memory.listThreads({\n filter: { resourceId, metadata: { factorySessionId: sessionId, [MOVE_PENDING_KEY]: true } },\n perPage: false,\n });\n for (const thread of interrupted) {\n if (thread.resourceId === sessionId) continue; // listed under the session id below\n await moveThread(deps, thread, thread.resourceId);\n report.threads += 1;\n }\n const { threads } = await deps.memory.listThreads({ filter: { resourceId: sessionId }, perPage: false });\n // A private session's stamps don't count under its Factory, so only its own\n // thread moves there; its other threads stay listed under its id.\n const stampsCount = sessionStampCounts(session, resourceId);\n for (const thread of threads) {\n if (!stampsCount && thread.id !== sessionId) continue;\n // Tag before moving: once moved, the thread is no longer found under the session id.\n const metadata = { ...thread.metadata, factorySessionId: sessionId, [MOVE_PENDING_KEY]: true };\n await deps.memory.patchThread({ id: thread.id, metadata });\n await moveThread(deps, { ...thread, metadata }, resourceId);\n report.threads += 1;\n }\n report.runBindings += await deps.workItems.moveRunBindingsToResource({ sessionId, resourceId });\n if (deps.integrations) {\n report.subscriptions += await deps.integrations.moveSubscriptionsToResource({\n fromResourceId: sessionId,\n toResourceId: resourceId,\n });\n }\n // Reported once, on the run that moves the session's threads.\n if (\n threads.length > 0 &&\n deps.memory.supportsObservationalMemory &&\n (await deps.memory.getObservationalMemory(null, sessionId))\n ) {\n report.resourceObservationsLeft.push(sessionId);\n console.warn(\n `[factory] session resource migration: session ${sessionId} has resource-scoped observational memory; ` +\n `it stays under resource ${sessionId} and is not carried into ${resourceId}`,\n );\n }\n if (!deps.integrations) {\n report.subscriptionsPending.push(sessionId);\n continue;\n }\n await deps.sessions.markResourcesMigrated(sessionId);\n } catch (error) {\n report.failed.push(sessionId);\n console.warn(\n `[factory] session resource migration: session ${sessionId} not moved: ${error instanceof Error ? error.message : error}`,\n );\n } finally {\n if (report.sessions < sessions.length && Date.now() - lastProgressAt >= PROGRESS_LOG_INTERVAL_MS) {\n lastProgressAt = Date.now();\n console.info(\n `[factory] session resource migration: ${report.sessions}/${sessions.length} sessions checked, ` +\n `${report.threads} threads moved`,\n );\n }\n }\n }\n\n if (\n report.threads +\n report.runBindings +\n report.subscriptions +\n report.skipped.length +\n report.failed.length +\n report.subscriptionsPending.length >\n 0\n ) {\n console.info(\n `[factory] session resource migration: ${report.threads} threads, ${report.runBindings} run bindings, ` +\n `${report.subscriptions} subscriptions moved; ${report.skipped.length} Factory sessions without a Factory skipped; ` +\n `${report.failed.length} sessions failed; ${report.subscriptionsPending.length} sessions wait for integrations ` +\n `to move their subscriptions`,\n );\n }\n return report;\n}\n\nexport interface SessionVisibilityBackfillDeps {\n sessions: {\n listSessionsAwaitingVisibilityCheck(): Promise<SourceControlSession[]>;\n markVisibilityChecked(sessionId: string, options: { makePrivate: boolean }): Promise<void>;\n };\n workItems: Pick<SessionResourceMigrationDeps['workItems'], 'listRunBoundItems'>;\n memory: Pick<MemoryStorage, 'getThreadById'>;\n}\n\n/**\n * Mark shared user sessions private when their conversation lives on their owner's resource.\n * The resource already keeps teammates out of such a session; this makes lists agree, so they\n * stop seeing a session they can't open. Sessions shared onto their Factory, runs, Slack threads\n * and side sessions are left alone. Each session is checked once: new sessions start checked,\n * and a session that throws stays unchecked so the next start retries it.\n */\nexport async function privatizeOwnerResourceSessions(deps: SessionVisibilityBackfillDeps): Promise<number> {\n let privatized = 0;\n for (const session of await deps.sessions.listSessionsAwaitingVisibilityCheck()) {\n try {\n let makePrivate = false;\n if (session.visibility !== 'private') {\n const { owner } = sessionMemoryResource(session, await deps.workItems.listRunBoundItems(session.sessionId));\n const thread = owner === 'user' ? await deps.memory.getThreadById({ threadId: session.sessionId }) : null;\n makePrivate = thread?.resourceId === session.userId;\n }\n await deps.sessions.markVisibilityChecked(session.sessionId, { makePrivate });\n if (makePrivate) privatized += 1;\n } catch (error) {\n console.warn(\n `[factory] session visibility check: session ${session.sessionId} not checked: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n if (privatized > 0) {\n console.info(`[factory] session visibility check: ${privatized} sessions on their owner's memory made private`);\n }\n return privatized;\n}\n\nasync function moveThread(\n deps: SessionResourceMigrationDeps,\n thread: StorageThreadType,\n resourceId: string,\n): Promise<void> {\n await deps.threads.updateThreadResourceId({ threadId: thread.id, resourceId });\n // Stores merge thread metadata, so the flag is switched off rather than removed.\n await deps.memory.patchThread({ id: thread.id, metadata: { ...thread.metadata, [MOVE_PENDING_KEY]: false } });\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;CAEF,IAAI,aAAa,GACf,QAAQ,KAAK,uCAAuC,WAAW,+CAA+C;CAEhH,OAAO;AACT;AAEA,eAAe,WACb,MACA,QACA,YACe;CACf,MAAM,KAAK,QAAQ,uBAAuB;EAAE,UAAU,OAAO;EAAI;CAAW,CAAC;CAE7E,MAAM,KAAK,OAAO,YAAY;EAAE,IAAI,OAAO;EAAI,UAAU;GAAE,GAAG,OAAO;IAAW,mBAAmB;EAAM;CAAE,CAAC;AAC9G"}
|
|
@@ -63,6 +63,15 @@ export type FactoryRunUsage = {
|
|
|
63
63
|
status: 'unreported';
|
|
64
64
|
};
|
|
65
65
|
export declare function listSessionOpenRuns(session: RunEndCaptureSession): Promise<FactoryOpenRun[]>;
|
|
66
|
+
/** The open-run ledger of `threadId`, whichever thread the session is on now. */
|
|
67
|
+
export declare function listThreadOpenRuns(session: {
|
|
68
|
+
readonly thread: {
|
|
69
|
+
getSettingOn(args: {
|
|
70
|
+
threadId: string;
|
|
71
|
+
key: string;
|
|
72
|
+
}): Promise<unknown>;
|
|
73
|
+
};
|
|
74
|
+
}, threadId: string): Promise<FactoryOpenRun[]>;
|
|
66
75
|
export declare function waitForSessionRunAudit(session: RunEndCaptureSession): Promise<void>;
|
|
67
76
|
export declare function recordSessionRunStart(session: RunEndCaptureSession, { audit, run, actorType, observedEnd, }: {
|
|
68
77
|
audit: AuditRecorder;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-audit.d.ts","sourceRoot":"","sources":["../../src/session/run-audit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAExE,eAAO,MAAM,yBAAyB,oBAAoB,CAAC;AAE3D,QAAA,M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,OAAO,EAAE,oBAAoB,EAAE,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,aAAa,CAAA;CAAE,GAAG,MAAM,IAAI,CAcnH"}
|
|
@@ -95,6 +95,14 @@ async function listSessionOpenRuns(session) {
|
|
|
95
95
|
const stored = await session.thread.getSetting({ key: FACTORY_OPEN_RUNS_SETTING });
|
|
96
96
|
return z.array(factoryOpenRunSchema).parse(stored ?? []);
|
|
97
97
|
}
|
|
98
|
+
/** The open-run ledger of `threadId`, whichever thread the session is on now. */
|
|
99
|
+
async function listThreadOpenRuns(session, threadId) {
|
|
100
|
+
const stored = await session.thread.getSettingOn({
|
|
101
|
+
threadId,
|
|
102
|
+
key: FACTORY_OPEN_RUNS_SETTING
|
|
103
|
+
});
|
|
104
|
+
return z.array(factoryOpenRunSchema).parse(stored ?? []);
|
|
105
|
+
}
|
|
98
106
|
async function waitForSessionRunAudit(session) {
|
|
99
107
|
await (pendingWrites.get(session) ?? Promise.resolve());
|
|
100
108
|
}
|
|
@@ -209,6 +217,6 @@ function observeSessionRunEnd(session, { audit }) {
|
|
|
209
217
|
serializeRunAudit(session, () => recordRunEnds(session, audit, event.reason, void 0, turn));
|
|
210
218
|
});
|
|
211
219
|
}
|
|
212
|
-
export { FACTORY_OPEN_RUNS_SETTING, FACTORY_OPEN_RUN_STALE_MS, FACTORY_RUN_USAGE_STEPS_JSON_BUDGET, heartbeatSessionOpenRun, isOpenRunLiveElsewhere, listSessionOpenRuns, observeSessionRunEnd, recordSessionRunStart, waitForSessionRunAudit };
|
|
220
|
+
export { FACTORY_OPEN_RUNS_SETTING, FACTORY_OPEN_RUN_STALE_MS, FACTORY_RUN_USAGE_STEPS_JSON_BUDGET, heartbeatSessionOpenRun, isOpenRunLiveElsewhere, listSessionOpenRuns, listThreadOpenRuns, observeSessionRunEnd, recordSessionRunStart, waitForSessionRunAudit };
|
|
213
221
|
|
|
214
222
|
//# sourceMappingURL=run-audit.js.map
|