@mastra/factory 0.28.0-alpha.8 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +61 -42
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/capabilities/version-control.d.ts +6 -1
  14. package/dist/capabilities/version-control.d.ts.map +1 -1
  15. package/dist/environment/build-runner.d.ts +13 -2
  16. package/dist/environment/build-runner.d.ts.map +1 -1
  17. package/dist/environment/build-runner.js +42 -0
  18. package/dist/environment/build-runner.js.map +1 -1
  19. package/dist/environment/build-schedule.js +1 -1
  20. package/dist/environment/build-schedule.js.map +1 -1
  21. package/dist/environment/build-workflow.d.ts +6 -4
  22. package/dist/environment/build-workflow.d.ts.map +1 -1
  23. package/dist/environment/build-workflow.js +70 -66
  24. package/dist/environment/build-workflow.js.map +1 -1
  25. package/dist/environment/build.d.ts +22 -7
  26. package/dist/environment/build.d.ts.map +1 -1
  27. package/dist/environment/build.js +73 -15
  28. package/dist/environment/build.js.map +1 -1
  29. package/dist/environment/heads.d.ts +1 -1
  30. package/dist/environment/heads.d.ts.map +1 -1
  31. package/dist/environment/heads.js +4 -1
  32. package/dist/environment/heads.js.map +1 -1
  33. package/dist/environment/repository-access.d.ts +13 -0
  34. package/dist/environment/repository-access.d.ts.map +1 -0
  35. package/dist/environment/repository-access.js +55 -0
  36. package/dist/environment/repository-access.js.map +1 -0
  37. package/dist/factory.d.ts +5 -2
  38. package/dist/factory.d.ts.map +1 -1
  39. package/dist/factory.js +32 -26
  40. package/dist/factory.js.map +1 -1
  41. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  42. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  43. package/dist/integrations/github/sandbox-release.js +16 -1
  44. package/dist/integrations/github/sandbox-release.js.map +1 -1
  45. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  46. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  47. package/dist/integrations/platform/github/integration.js +137 -105
  48. package/dist/integrations/platform/github/integration.js.map +1 -1
  49. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  50. package/dist/integrations/platform/jira/integration.js +5 -1
  51. package/dist/integrations/platform/jira/integration.js.map +1 -1
  52. package/dist/integrations/slack/integration.d.ts.map +1 -1
  53. package/dist/integrations/slack/integration.js +7 -4
  54. package/dist/integrations/slack/integration.js.map +1 -1
  55. package/dist/mcp/routes.d.ts.map +1 -1
  56. package/dist/mcp/routes.js +3 -5
  57. package/dist/mcp/routes.js.map +1 -1
  58. package/dist/routes/board-snapshot.d.ts +17 -1
  59. package/dist/routes/board-snapshot.d.ts.map +1 -1
  60. package/dist/routes/board-snapshot.js +54 -7
  61. package/dist/routes/board-snapshot.js.map +1 -1
  62. package/dist/routes/boards.d.ts +2 -3
  63. package/dist/routes/boards.d.ts.map +1 -1
  64. package/dist/routes/boards.js.map +1 -1
  65. package/dist/routes/contracts.d.ts +102 -0
  66. package/dist/routes/contracts.d.ts.map +1 -1
  67. package/dist/routes/contracts.js +96 -6
  68. package/dist/routes/contracts.js.map +1 -1
  69. package/dist/routes/projects.d.ts.map +1 -1
  70. package/dist/routes/projects.js +5 -0
  71. package/dist/routes/projects.js.map +1 -1
  72. package/dist/routes/sandbox-envs.d.ts +2 -0
  73. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  74. package/dist/routes/sandbox-envs.js +3 -0
  75. package/dist/routes/sandbox-envs.js.map +1 -1
  76. package/dist/routes/source-control-settings.d.ts +2 -0
  77. package/dist/routes/source-control-settings.d.ts.map +1 -1
  78. package/dist/routes/source-control-settings.js +5 -0
  79. package/dist/routes/source-control-settings.js.map +1 -1
  80. package/dist/routes/surface.d.ts +2 -0
  81. package/dist/routes/surface.d.ts.map +1 -1
  82. package/dist/routes/surface.js +2 -1
  83. package/dist/routes/surface.js.map +1 -1
  84. package/dist/routes/work-item-activity.d.ts +11 -0
  85. package/dist/routes/work-item-activity.d.ts.map +1 -0
  86. package/dist/routes/work-item-activity.js +25 -0
  87. package/dist/routes/work-item-activity.js.map +1 -0
  88. package/dist/routes/work-item-selection.d.ts +18 -0
  89. package/dist/routes/work-item-selection.d.ts.map +1 -0
  90. package/dist/routes/work-item-selection.js +61 -0
  91. package/dist/routes/work-item-selection.js.map +1 -0
  92. package/dist/routes/work-item-starters.d.ts +29 -0
  93. package/dist/routes/work-item-starters.d.ts.map +1 -0
  94. package/dist/routes/work-item-starters.js +169 -0
  95. package/dist/routes/work-item-starters.js.map +1 -0
  96. package/dist/routes/work-items.d.ts.map +1 -1
  97. package/dist/routes/work-items.js +162 -15
  98. package/dist/routes/work-items.js.map +1 -1
  99. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  100. package/dist/rules/dispatch-errors.js +4 -0
  101. package/dist/rules/dispatch-errors.js.map +1 -1
  102. package/dist/rules/dispatcher.d.ts +2 -1
  103. package/dist/rules/dispatcher.d.ts.map +1 -1
  104. package/dist/rules/dispatcher.js +84 -16
  105. package/dist/rules/dispatcher.js.map +1 -1
  106. package/dist/rules/processor.d.ts +2 -0
  107. package/dist/rules/processor.d.ts.map +1 -1
  108. package/dist/rules/processor.js +18 -4
  109. package/dist/rules/processor.js.map +1 -1
  110. package/dist/rules/transition-service.d.ts +20 -2
  111. package/dist/rules/transition-service.d.ts.map +1 -1
  112. package/dist/rules/transition-service.js +40 -18
  113. package/dist/rules/transition-service.js.map +1 -1
  114. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  115. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  116. package/dist/sandbox/context-sandboxes.js +120 -0
  117. package/dist/sandbox/context-sandboxes.js.map +1 -0
  118. package/dist/sandbox/session-retirement.d.ts +11 -4
  119. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  120. package/dist/sandbox/session-retirement.js +39 -13
  121. package/dist/sandbox/session-retirement.js.map +1 -1
  122. package/dist/session/live-sessions.d.ts +1 -1
  123. package/dist/session/live-sessions.d.ts.map +1 -1
  124. package/dist/session/live-sessions.js +12 -2
  125. package/dist/session/live-sessions.js.map +1 -1
  126. package/dist/storage/domains/boards/base.d.ts +25 -5
  127. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  128. package/dist/storage/domains/boards/base.js +57 -20
  129. package/dist/storage/domains/boards/base.js.map +1 -1
  130. package/dist/storage/domains/projects/base.d.ts +8 -2
  131. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  132. package/dist/storage/domains/projects/base.js +21 -4
  133. package/dist/storage/domains/projects/base.js.map +1 -1
  134. package/dist/storage/domains/work-items/base.d.ts +47 -6
  135. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  136. package/dist/storage/domains/work-items/base.js +161 -17
  137. package/dist/storage/domains/work-items/base.js.map +1 -1
  138. package/dist/storage/domains/work-items/cards.d.ts +1 -0
  139. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  140. package/dist/storage/domains/work-items/cards.js +32 -8
  141. package/dist/storage/domains/work-items/cards.js.map +1 -1
  142. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  143. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  144. package/dist/storage/domains/work-items/legacy-review.js +62 -3
  145. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  146. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
  147. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  148. package/dist/storage/domains/work-items/work-item-schema.js +46 -18
  149. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  150. package/dist/tools/annotations.d.ts.map +1 -1
  151. package/dist/tools/annotations.js +4 -0
  152. package/dist/tools/annotations.js.map +1 -1
  153. package/dist/tools/audit-events-tool.d.ts +29 -0
  154. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  155. package/dist/tools/audit-events-tool.js +180 -0
  156. package/dist/tools/audit-events-tool.js.map +1 -0
  157. package/dist/tools/index.d.ts +2 -1
  158. package/dist/tools/index.d.ts.map +1 -1
  159. package/dist/tools/index.js +2 -0
  160. package/dist/tools/index.js.map +1 -1
  161. package/dist/tools/permissions.d.ts.map +1 -1
  162. package/dist/tools/permissions.js +1 -0
  163. package/dist/tools/permissions.js.map +1 -1
  164. package/dist/tools/sessions-state-processor.js +1 -1
  165. package/dist/tools/sessions-state-processor.js.map +1 -1
  166. package/dist/work-items/board-check.d.ts +11 -0
  167. package/dist/work-items/board-check.d.ts.map +1 -0
  168. package/dist/work-items/board-check.js +20 -0
  169. package/dist/work-items/board-check.js.map +1 -0
  170. package/dist/work-items/related-cards.d.ts +21 -0
  171. package/dist/work-items/related-cards.d.ts.map +1 -0
  172. package/dist/work-items/related-cards.js +45 -0
  173. package/dist/work-items/related-cards.js.map +1 -0
  174. package/dist/work-items/split-migration.d.ts.map +1 -1
  175. package/dist/work-items/split-migration.js +6 -2
  176. package/dist/work-items/split-migration.js.map +1 -1
  177. package/dist/workspace.d.ts +0 -1
  178. package/dist/workspace.d.ts.map +1 -1
  179. package/dist/workspace.js +49 -32
  180. package/dist/workspace.js.map +1 -1
  181. package/factory-skills/factory-build/SKILL.md +1 -1
  182. package/factory-skills/factory-self-review/SKILL.md +1 -1
  183. package/factory-skills/factory-triage/SKILL.md +4 -4
  184. package/package.json +16 -16
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-schema.js","names":[],"sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nimport type { FactoryTriageType } from '../../../rules/types.js';\n\nexport type WorkItemProvider =\n | 'github'\n | 'gitlab'\n | 'jira'\n | 'linear'\n | 'slack'\n | 'incidentio'\n | 'factory'\n | (string & {});\n\n/** The work itself; external identities and facts belong to its sources. */\nexport const FACTORY_WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n title: { type: 'text' },\n description: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_work_items_org_project_idx', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** Several external records can describe one work item. Native work has no source. */\nexport const FACTORY_WORK_ITEM_SOURCES_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_sources',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n provider: { type: 'text' },\n integration_id: { type: 'text' },\n source_type: { type: 'text' },\n workspace_id: { type: 'text', nullable: true },\n external_id: { type: 'text' },\n source_key: { type: 'text', nullable: true },\n url: { type: 'text', nullable: true },\n key: { type: 'text', nullable: true },\n state: { type: 'text', nullable: true },\n labels: { type: 'json' },\n author: { type: 'text', nullable: true },\n metadata: { type: 'json', nullable: true },\n /** `origin` for the record the work item was created from, `attached` for one added later. Null (rows written before this column) reads as `origin`. */\n role: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n synced_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_work_item_sources_project_provider_external_unique',\n columns: ['org_id', 'factory_project_id', 'provider', 'external_id'],\n },\n ],\n indexes: [\n { name: 'factory_work_item_sources_work_item_idx', columns: ['work_item_id'] },\n { name: 'factory_work_item_sources_source_key_idx', columns: ['source_key'] },\n ],\n};\n\n/** Placement/process state. Its id preserves every legacy card reference. */\nexport const FACTORY_BOARD_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_board_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n triage_type: { type: 'text', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n board: { type: 'text', nullable: true },\n parent_board_item_id: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n migrated_from_updated_at: { type: 'timestamp', nullable: true },\n migrated_from_hash: { type: 'text', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_items_work_item_unique', columns: ['work_item_id'] }],\n indexes: [\n {\n name: 'factory_board_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'factory_board_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_board_item_id'],\n },\n ],\n};\n\nexport interface WorkItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n title: string;\n description: string | null;\n parent_work_item_id: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\nexport interface WorkItemSourceDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n provider: WorkItemProvider;\n integration_id: string;\n source_type: string;\n workspace_id: string | null;\n external_id: string;\n source_key: string | null;\n url: string | null;\n key: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n role?: WorkItemSourceRole | null;\n revision: number;\n synced_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nexport type WorkItemSourceRole = 'origin' | 'attached';\n\nexport interface WorkItemSourceRow {\n id: string;\n workItemId: string;\n provider: WorkItemProvider;\n integrationId: string;\n sourceType: string;\n workspaceId: string | null;\n externalId: string;\n sourceKey: string | null;\n key: string | null;\n url: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function primarySource(card: { workItem: { sources: readonly WorkItemSourceRow[] } }): WorkItemSourceRow | null {\n return card.workItem.sources[0] ?? null;\n}\n\nexport interface WorkItemRow {\n sources: WorkItemSourceRow[];\n id: string;\n orgId: string;\n factoryProjectId: string;\n provider: WorkItemProvider;\n externalId: string;\n key: string | null;\n url: string | null;\n title: string;\n state: string | null;\n labels: string[];\n author: string | null;\n parentWorkItemId: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface BoardItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n triage_type: FactoryTriageType | null;\n accepted_at: Date | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n board: string | null;\n parent_board_item_id: string | null;\n stages: string[];\n stage_history: unknown[];\n sessions: Record<string, unknown>;\n metadata: Record<string, unknown> | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n migrated_from_updated_at: Date | null;\n migrated_from_hash: string | null;\n}\n\n/** Serializes first-copy migration with deletion without locking an entire project's cards. */\nexport const FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** Deleted card ids prevent the boot migration resurrecting frozen legacy rows. */\nexport const FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA: CollectionSchema = {\n name: 'factory_board_item_tombstones',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** The pre-split card table. Frozen: only the split migration reads it. */\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n // Retained for existing tables; claims no longer govern work-item identity.\n claim_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n description: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n // Retired hands-off plan grant: plans are approved per board (`exitTool`).\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n // Retired comment summaries: kept so replicas still on the old release can write them.\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n {\n // One live card per claimed external record per org. NULL keys never\n // collide, so unclaimed cards are unaffected.\n name: 'work_items_org_claim_key_unique',\n columns: ['org_id', 'claim_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n {\n // Finds the newest legacy write without a scan, so a finished split can be confirmed at boot.\n name: 'work_items_updated_at_id_idx',\n columns: ['updated_at', 'id'],\n },\n ],\n};\n\n/** Records the newest legacy row a finished split pass covered; later boots skip unchanged legacy tables. */\nexport const FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_state',\n columns: {\n id: { type: 'text', primaryKey: true },\n legacy_updated_at: { type: 'timestamp', nullable: true },\n legacy_id: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp' },\n },\n};\n"],"mappings":";;AAeA,MAAa,4BAA8C;CACzD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,OAAO,EAAE,MAAM,OAAO;EACtB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,qBAAqB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACpD,UAAU;GAAE,MAAM;GAAW,SAAS;EAAE;EACxC,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,SAAS,CAAC;EAAE,MAAM;EAAsC,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AACrG;;AAGA,MAAa,mCAAqD;CAChE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,cAAc,EAAE,MAAM,OAAO;EAC7B,UAAU,EAAE,MAAM,OAAO;EACzB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,aAAa,EAAE,MAAM,OAAO;EAC5B,cAAc;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC7C,aAAa,EAAE,MAAM,OAAO;EAC5B,YAAY;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC3C,KAAK;GAAE,MAAM;GAAQ,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O;EACvB,eAAe,EAAE,MAAM,OAAO;EAC9B,UAAU,EAAE,MAAM,OAAO;EACzB,UAAU;GAAE,MAAM;GAAQ,UAAU;EAAK;EACzC,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,mBAAmB;GAAE,MAAM;GAAa,UAAU;EAAK;EAEvD,sBAAsB;GAAE,MAAM;GAAa,UAAU;EAAK;EAC1D,aAAa;GAAE,MAAM;GAAa,UAAU;EAAK;EAEjD,eAAe;GAAE,MAAM;GAAW,SAAS;EAAE;EAC7C,kBAAkB;GAAE,MAAM;GAAa,UAAU;EAAK;EACtD,UAAU;GAAE,MAAM;GAAW,SAAS;EAAE;EACxC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CACb;EACE,MAAM;EACN,SAAS,CAAC,sBAAsB,YAAY;CAC9C,GACA;EAGE,MAAM;EACN,SAAS,CAAC,UAAU,WAAW;CACjC,CACF;CACA,SAAS;EACP;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;IAAc;GAAI;EAC9D;EACA;GACE,MAAM;GACN,SAAS;IAAC;IAAU;IAAsB;GAAqB;EACjE;EACA;GAGE,MAAM;GACN,SAAS,CAAC,YAAY;EACxB;EACA;GAEE,MAAM;GACN,SAAS,CAAC,cAAc,IAAI;EAC9B;CACF;AACF;;AAGA,MAAa,uCAAyD;CACpE,MAAM;CACN,SAAS;EACP,IAAI;GAAE,MAAM;GAAQ,YAAY;EAAK;EACrC,mBAAmB;GAAE,MAAM;GAAa,UAAU;EAAK;EACvD,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,cAAc,EAAE,MAAM,YAAY;CACpC;AACF"}
1
+ {"version":3,"file":"work-item-schema.js","names":[],"sources":["../../../../src/storage/domains/work-items/work-item-schema.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\nimport type { FactoryTriageType } from '../../../rules/types.js';\n\nexport type WorkItemProvider =\n | 'github'\n | 'gitlab'\n | 'jira'\n | 'linear'\n | 'slack'\n | 'incidentio'\n | 'factory'\n | (string & {});\n\n/** The work itself; external identities and facts belong to its sources. */\nexport const FACTORY_WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n title: { type: 'text' },\n description: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_work_items_org_project_idx', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** Several external records can describe one work item. Native work has no source. */\nexport const FACTORY_WORK_ITEM_SOURCES_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_sources',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n provider: { type: 'text' },\n integration_id: { type: 'text' },\n source_type: { type: 'text' },\n workspace_id: { type: 'text', nullable: true },\n external_id: { type: 'text' },\n source_key: { type: 'text', nullable: true },\n url: { type: 'text', nullable: true },\n key: { type: 'text', nullable: true },\n state: { type: 'text', nullable: true },\n labels: { type: 'json' },\n author: { type: 'text', nullable: true },\n metadata: { type: 'json', nullable: true },\n /** `origin` for the record the work item was created from, `attached` for one added later. Null (rows written before this column) reads as `origin`. */\n role: { type: 'text', nullable: true },\n revision: { type: 'integer', default: 1 },\n synced_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_work_item_sources_project_provider_external_unique',\n columns: ['org_id', 'factory_project_id', 'provider', 'external_id'],\n },\n ],\n indexes: [\n { name: 'factory_work_item_sources_work_item_idx', columns: ['work_item_id'] },\n { name: 'factory_work_item_sources_source_key_idx', columns: ['source_key'] },\n ],\n};\n\n/** Placement/process state. Its id preserves every legacy card reference. */\nexport const FACTORY_BOARD_ITEMS_SCHEMA: CollectionSchema = {\n name: 'factory_board_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n triage_type: { type: 'text', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n board: { type: 'text', nullable: true },\n parent_board_item_id: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n migrated_from_updated_at: { type: 'timestamp', nullable: true },\n migrated_from_hash: { type: 'text', nullable: true },\n /** Moves on every change to the card, in any of its tables; board reloads read rows changed since. */\n changed_at: { type: 'timestamp', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_items_work_item_unique', columns: ['work_item_id'] }],\n indexes: [\n {\n name: 'factory_board_items_project_changed_at_idx',\n columns: ['org_id', 'factory_project_id', 'changed_at'],\n },\n {\n name: 'factory_board_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'factory_board_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_board_item_id'],\n },\n ],\n};\n\nexport interface WorkItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n title: string;\n description: string | null;\n parent_work_item_id: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\nexport interface WorkItemSourceDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n provider: WorkItemProvider;\n integration_id: string;\n source_type: string;\n workspace_id: string | null;\n external_id: string;\n source_key: string | null;\n url: string | null;\n key: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n role?: WorkItemSourceRole | null;\n revision: number;\n synced_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nexport type WorkItemSourceRole = 'origin' | 'attached';\n\nexport interface WorkItemSourceRow {\n id: string;\n workItemId: string;\n provider: WorkItemProvider;\n integrationId: string;\n sourceType: string;\n workspaceId: string | null;\n externalId: string;\n sourceKey: string | null;\n key: string | null;\n url: string | null;\n state: string | null;\n labels: string[];\n author: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function primarySource(card: { workItem: { sources: readonly WorkItemSourceRow[] } }): WorkItemSourceRow | null {\n return card.workItem.sources[0] ?? null;\n}\n\nexport interface WorkItemRow {\n sources: WorkItemSourceRow[];\n id: string;\n orgId: string;\n factoryProjectId: string;\n provider: WorkItemProvider;\n externalId: string;\n key: string | null;\n url: string | null;\n title: string;\n state: string | null;\n labels: string[];\n author: string | null;\n parentWorkItemId: string | null;\n metadata: Record<string, unknown> | null;\n revision: number;\n syncedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface BoardItemDbRecord extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n triage_type: FactoryTriageType | null;\n accepted_at: Date | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n board: string | null;\n parent_board_item_id: string | null;\n stages: string[];\n stage_history: unknown[];\n sessions: Record<string, unknown>;\n metadata: Record<string, unknown> | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n migrated_from_updated_at: Date | null;\n migrated_from_hash: string | null;\n changed_at?: Date | null;\n}\n\n/** Serializes first-copy migration with deletion without locking an entire project's cards. */\nexport const FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n },\n};\n\n/** Deleted card ids prevent the boot migration resurrecting frozen legacy rows. */\nexport const FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA: CollectionSchema = {\n name: 'factory_board_item_tombstones',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n deleted_at: { type: 'timestamp', nullable: true },\n },\n indexes: [\n {\n name: 'factory_board_item_tombstones_project_deleted_at_idx',\n columns: ['org_id', 'factory_project_id', 'deleted_at'],\n },\n ],\n};\n\n/** The pre-split card table. Frozen: only the split migration reads it. */\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n // Retained for existing tables; claims no longer govern work-item identity.\n claim_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n description: { type: 'text', nullable: true },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n // Retired hands-off plan grant: plans are approved per board (`exitTool`).\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n // Retired comment summaries: kept so replicas still on the old release can write them.\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n {\n // One live card per claimed external record per org. NULL keys never\n // collide, so unclaimed cards are unaffected.\n name: 'work_items_org_claim_key_unique',\n columns: ['org_id', 'claim_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n {\n // Finds the newest legacy write without a scan, so a finished split can be confirmed at boot.\n name: 'work_items_updated_at_id_idx',\n columns: ['updated_at', 'id'],\n },\n ],\n};\n\n/** Records the newest legacy row a finished split pass covered; later boots skip unchanged legacy tables. */\nexport const FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_split_state',\n columns: {\n id: { type: 'text', primaryKey: true },\n legacy_updated_at: { type: 'timestamp', nullable: true },\n legacy_id: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp' },\n },\n};\n"],"mappings":";;AAeA,MAAa,4BAA8C;CACzD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,OAAO,EAAE,MAAM,OAAO;EACtB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,qBAAqB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACpD,UAAU;GAAE,MAAM;GAAW,SAAS;EAAE;EACxC,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,SAAS,CAAC;EAAE,MAAM;EAAsC,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AACrG;;AAGA,MAAa,mCAAqD;CAChE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,M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;GACN,SAAS;IAAC;IAAU;IAAsB;GAAqB;EACjE;EACA;GAGE,MAAM;GACN,SAAS,CAAC,YAAY;EACxB;EACA;GAEE,MAAM;GACN,SAAS,CAAC,cAAc,IAAI;EAC9B;CACF;AACF;;AAGA,MAAa,uCAAyD;CACpE,MAAM;CACN,SAAS;EACP,IAAI;GAAE,MAAM;GAAQ,YAAY;EAAK;EACrC,mBAAmB;GAAE,MAAM;GAAa,UAAU;EAAK;EACvD,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,cAAc,EAAE,MAAM,YAAY;CACpC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"annotations.d.ts","sourceRoot":"","sources":["../../src/tools/annotations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAY1D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAkBpE,CAAC"}
1
+ {"version":3,"file":"annotations.d.ts","sourceRoot":"","sources":["../../src/tools/annotations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAY1D;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAmBpE,CAAC"}
@@ -36,6 +36,10 @@ const FACTORY_TOOL_ANNOTATIONS = {
36
36
  ...read,
37
37
  title: "List items that need attention"
38
38
  },
39
+ factory_list_audit_events: {
40
+ ...read,
41
+ title: "List audit events"
42
+ },
39
43
  factory_create_work_item: {
40
44
  ...additive,
41
45
  title: "Create a work item"
@@ -1 +1 @@
1
- {"version":3,"file":"annotations.js","names":[],"sources":["../../src/tools/annotations.ts"],"sourcesContent":["import type { ToolAnnotations } from '@mastra/core/tools';\n\nconst read: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst additive: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\nconst toggle: ToolAnnotations = { ...additive, idempotentHint: true };\nconst changes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };\n\n/**\n * MCP hints for each Factory tool, so clients like ChatGPT can tell lookups\n * from writes and ask before a tool changes or discards state.\n */\nexport const FACTORY_TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {\n factory_list_work_items: { ...read, title: 'List work items' },\n factory_inspect_work_item: { ...read, title: 'Inspect a work item' },\n factory_list_attention: { ...read, title: 'List items that need attention' },\n factory_create_work_item: { ...additive, title: 'Create a work item' },\n factory_update_work_item: { ...changes, title: 'Update a work item' },\n factory_transition_work_item: { ...changes, title: 'Move a work item to another stage' },\n factory_retry_decision: { ...additive, title: 'Retry a failed decision' },\n factory_dismiss_decision: { ...changes, title: 'Dismiss a decision' },\n factory_resolve_proposal: { ...changes, title: 'Approve or reject a proposal' },\n factory_subscribe_work_item: { ...toggle, title: 'Follow a work item' },\n factory_unsubscribe_work_item: { ...toggle, title: 'Stop following a work item' },\n factory_start_session: { ...additive, openWorldHint: true, title: 'Start an agent session' },\n factory_signal_session: { ...additive, openWorldHint: true, title: 'Message a running session' },\n factory_message_origin: { ...additive, title: 'Reply to the session that started this one' },\n factory_answer_approval: { ...changes, openWorldHint: true, title: 'Answer a session approval request' },\n search: { ...read, title: 'Search work items' },\n fetch: { ...read, title: 'Fetch a work item' },\n};\n"],"mappings":";AAEA,MAAM,OAAwB;CAC5B,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;AACA,MAAM,WAA4B;CAAE,cAAc;CAAO,iBAAiB;CAAO,eAAe;AAAM;AACtG,MAAM,SAA0B;CAAE,GAAG;CAAU,gBAAgB;AAAK;AACpE,MAAM,UAA2B;CAAE,cAAc;CAAO,iBAAiB;CAAM,eAAe;AAAM;;;;;AAMpG,MAAa,2BAA4D;CACvE,yBAAyB;EAAE,GAAG;EAAM,OAAO;CAAkB;CAC7D,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAsB;CACnE,wBAAwB;EAAE,GAAG;EAAM,OAAO;CAAiC;CAC3E,0BAA0B;EAAE,GAAG;EAAU,OAAO;CAAqB;CACrE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,8BAA8B;EAAE,GAAG;EAAS,OAAO;CAAoC;CACvF,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA0B;CACxE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAA+B;CAC9E,6BAA6B;EAAE,GAAG;EAAQ,OAAO;CAAqB;CACtE,+BAA+B;EAAE,GAAG;EAAQ,OAAO;CAA6B;CAChF,uBAAuB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAAyB;CAC3F,wBAAwB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAA4B;CAC/F,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA6C;CAC3F,yBAAyB;EAAE,GAAG;EAAS,eAAe;EAAM,OAAO;CAAoC;CACvG,QAAQ;EAAE,GAAG;EAAM,OAAO;CAAoB;CAC9C,OAAO;EAAE,GAAG;EAAM,OAAO;CAAoB;AAC/C"}
1
+ {"version":3,"file":"annotations.js","names":[],"sources":["../../src/tools/annotations.ts"],"sourcesContent":["import type { ToolAnnotations } from '@mastra/core/tools';\n\nconst read: ToolAnnotations = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n};\nconst additive: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };\nconst toggle: ToolAnnotations = { ...additive, idempotentHint: true };\nconst changes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, openWorldHint: false };\n\n/**\n * MCP hints for each Factory tool, so clients like ChatGPT can tell lookups\n * from writes and ask before a tool changes or discards state.\n */\nexport const FACTORY_TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {\n factory_list_work_items: { ...read, title: 'List work items' },\n factory_inspect_work_item: { ...read, title: 'Inspect a work item' },\n factory_list_attention: { ...read, title: 'List items that need attention' },\n factory_list_audit_events: { ...read, title: 'List audit events' },\n factory_create_work_item: { ...additive, title: 'Create a work item' },\n factory_update_work_item: { ...changes, title: 'Update a work item' },\n factory_transition_work_item: { ...changes, title: 'Move a work item to another stage' },\n factory_retry_decision: { ...additive, title: 'Retry a failed decision' },\n factory_dismiss_decision: { ...changes, title: 'Dismiss a decision' },\n factory_resolve_proposal: { ...changes, title: 'Approve or reject a proposal' },\n factory_subscribe_work_item: { ...toggle, title: 'Follow a work item' },\n factory_unsubscribe_work_item: { ...toggle, title: 'Stop following a work item' },\n factory_start_session: { ...additive, openWorldHint: true, title: 'Start an agent session' },\n factory_signal_session: { ...additive, openWorldHint: true, title: 'Message a running session' },\n factory_message_origin: { ...additive, title: 'Reply to the session that started this one' },\n factory_answer_approval: { ...changes, openWorldHint: true, title: 'Answer a session approval request' },\n search: { ...read, title: 'Search work items' },\n fetch: { ...read, title: 'Fetch a work item' },\n};\n"],"mappings":";AAEA,MAAM,OAAwB;CAC5B,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;AACA,MAAM,WAA4B;CAAE,cAAc;CAAO,iBAAiB;CAAO,eAAe;AAAM;AACtG,MAAM,SAA0B;CAAE,GAAG;CAAU,gBAAgB;AAAK;AACpE,MAAM,UAA2B;CAAE,cAAc;CAAO,iBAAiB;CAAM,eAAe;AAAM;;;;;AAMpG,MAAa,2BAA4D;CACvE,yBAAyB;EAAE,GAAG;EAAM,OAAO;CAAkB;CAC7D,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAsB;CACnE,wBAAwB;EAAE,GAAG;EAAM,OAAO;CAAiC;CAC3E,2BAA2B;EAAE,GAAG;EAAM,OAAO;CAAoB;CACjE,0BAA0B;EAAE,GAAG;EAAU,OAAO;CAAqB;CACrE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,8BAA8B;EAAE,GAAG;EAAS,OAAO;CAAoC;CACvF,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA0B;CACxE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAAqB;CACpE,0BAA0B;EAAE,GAAG;EAAS,OAAO;CAA+B;CAC9E,6BAA6B;EAAE,GAAG;EAAQ,OAAO;CAAqB;CACtE,+BAA+B;EAAE,GAAG;EAAQ,OAAO;CAA6B;CAChF,uBAAuB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAAyB;CAC3F,wBAAwB;EAAE,GAAG;EAAU,eAAe;EAAM,OAAO;CAA4B;CAC/F,wBAAwB;EAAE,GAAG;EAAU,OAAO;CAA6C;CAC3F,yBAAyB;EAAE,GAAG;EAAS,eAAe;EAAM,OAAO;CAAoC;CACvG,QAAQ;EAAE,GAAG;EAAM,OAAO;CAAoB;CAC9C,OAAO;EAAE,GAAG;EAAM,OAAO;CAAoB;AAC/C"}
@@ -0,0 +1,29 @@
1
+ import type { SourceControlSessionLookup } from '../session/factory-session.js';
2
+ import type { FactoryReadToolDependencies } from './read-tools.js';
3
+ import type { FactoryToolScope } from './scope.js';
4
+ export interface FactoryAuditToolDependencies {
5
+ workItems: FactoryReadToolDependencies['workItems'];
6
+ audit: FactoryReadToolDependencies['audit'];
7
+ messaging?: FactoryReadToolDependencies['messaging'];
8
+ /** Finds the sessions an event names or an agent ran in, to leave out other people's private sessions. */
9
+ sessions?: Pick<SourceControlSessionLookup, 'getBySessionId'>;
10
+ }
11
+ /**
12
+ * Who did what in this Factory, from its audit trail. The trail is org-wide and
13
+ * its reads are unscoped by design, so this tool narrows what it hands back:
14
+ * only this Factory's events, never request context (IP, user agent), names but
15
+ * never emails, no metadata beyond what was acted on, and no events from or
16
+ * about another person's private session.
17
+ */
18
+ export declare function createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies): import("@mastra/core/tools").Tool<{
19
+ actor?: string | undefined;
20
+ includeAgentRuns?: boolean | undefined;
21
+ namespace?: "agent" | "board" | "git" | "intake" | "intake_route" | "run" | "sandbox_env" | "session" | "skill" | "work_item" | undefined;
22
+ actions?: ("factory.agent.commit" | "factory.agent.pr_opened" | "factory.agent.push" | "factory.agent.signaled" | "factory.board.created" | "factory.board.deleted" | "factory.board.reset" | "factory.board.updated" | "factory.git.commit" | "factory.git.pr_opened" | "factory.git.push" | "factory.intake.binding_updated" | "factory.intake.config_updated" | "factory.intake.label_route_updated" | "factory.intake_route.created" | "factory.intake_route.deleted" | "factory.intake_route.reordered" | "factory.intake_route.updated" | "factory.run.approved" | "factory.run.dismissed" | "factory.run.ended" | "factory.run.queued" | "factory.run.rejected" | "factory.run.retry" | "factory.run.started" | "factory.sandbox_env.deleted" | "factory.sandbox_env.set" | "factory.sandbox_env.updated" | "factory.session.owner_transferred" | "factory.skill.reverted" | "factory.skill.updated" | "factory.work_item.created" | "factory.work_item.deleted" | "factory.work_item.labels_reconciled" | "factory.work_item.stage_moved" | "factory.work_item.transition_rejected" | "factory.work_item.updated")[] | undefined;
23
+ workItem?: string | undefined;
24
+ since?: string | undefined;
25
+ until?: string | undefined;
26
+ cursor?: string | undefined;
27
+ limit?: number | undefined;
28
+ }, unknown, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "factory_list_audit_events", unknown>;
29
+ //# sourceMappingURL=audit-events-tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-events-tool.d.ts","sourceRoot":"","sources":["../../src/tools/audit-events-tool.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAUhF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AASnD,MAAM,WAAW,4BAA4B;IAC3C,SAAS,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACpD,KAAK,EAAE,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAC5C,SAAS,CAAC,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACrD,0GAA0G;IAC1G,QAAQ,CAAC,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;CAC/D;AA4CD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAE,4BAA4B;;;;;;;;;;kJAmEhG"}
@@ -0,0 +1,180 @@
1
+ import { auditActionsInNamespaces, auditNamespaces, isAuditAction } from "../storage/domains/audit/actions.js";
2
+ import { ACTOR_PROFILE_METADATA_KEY, auditCursorAt, decodeAuditAfterCursor, encodeAuditCursor } from "../storage/domains/audit/base.js";
3
+ import { findWorkItem, truncate, workItemNotFound, workItemRefSchema } from "./read-tools.js";
4
+ import { createTool } from "@mastra/core/tools";
5
+ import { z } from "zod";
6
+ // src/tools/audit-events-tool.ts
7
+ const DEFAULT_LIMIT = 25;
8
+ const PAGE_SIZE = 200;
9
+ /** Pages read per call before handing back a cursor, so a narrow filter can't scan the whole trail at once. */
10
+ const MAX_PAGES = 5;
11
+ const AGENT_ACTOR_PREFIX = "agent:";
12
+ const SESSION_ACTOR_PREFIX = "session:";
13
+ const namespaces = auditNamespaces();
14
+ const inputSchema = z.object({
15
+ actor: z.string().trim().min(1).max(200).optional().describe("\"me\", a user id, or an agent actor id like \"agent:<threadId>\". Only events this actor performed."),
16
+ includeAgentRuns: z.boolean().optional().describe("With a person as `actor`: also include what agents did in runs that person started."),
17
+ namespace: z.enum(namespaces).optional().describe("Only actions in this namespace, e.g. \"work_item\" or \"run\"."),
18
+ actions: z.array(z.string().refine(isAuditAction, { message: "Not a Factory audit action." })).min(1).max(50).optional().describe("Only these exact actions, e.g. [\"factory.work_item.stage_moved\"]."),
19
+ workItem: workItemRefSchema.optional().describe("Only events that acted on this work item (id or \"#123\")."),
20
+ since: z.iso.datetime({ offset: true }).optional().describe("Only events at or after this ISO time."),
21
+ until: z.iso.datetime({ offset: true }).optional().describe("Only events before this ISO time."),
22
+ cursor: z.string().min(1).max(200).optional().describe("`nextCursor` from a previous call, to read older events."),
23
+ limit: z.number().int().min(1).max(50).optional().describe(`Default ${DEFAULT_LIMIT}, max 50.`)
24
+ }).strict();
25
+ /** A display name stamped at record time, or nothing when it is an email (the fallback when a person has no name). */
26
+ function actorName(event) {
27
+ const profile = event.metadata?.[ACTOR_PROFILE_METADATA_KEY];
28
+ const name = typeof profile?.name === "string" ? profile.name.trim() : "";
29
+ return name && !name.includes("@") ? truncate(name, 600) : void 0;
30
+ }
31
+ function startedBy(event) {
32
+ const value = event.metadata?.startedBy;
33
+ return event.actorType === "agent" && typeof value === "string" ? value : void 0;
34
+ }
35
+ /**
36
+ * Who did what in this Factory, from its audit trail. The trail is org-wide and
37
+ * its reads are unscoped by design, so this tool narrows what it hands back:
38
+ * only this Factory's events, never request context (IP, user agent), names but
39
+ * never emails, no metadata beyond what was acted on, and no events from or
40
+ * about another person's private session.
41
+ */
42
+ function createAuditEventsTool(scope, deps) {
43
+ const project = {
44
+ orgId: scope.orgId,
45
+ factoryProjectId: scope.factoryProjectId
46
+ };
47
+ return createTool({
48
+ id: "factory_list_audit_events",
49
+ description: "List this Factory's audit events, newest first: who did what to which work item, run, branch or setting, and when. Filter by actor (\"me\" or a user id, optionally with the agent runs they started), action namespace or exact actions, work item, and time range. Pass `nextCursor` back as `cursor` for older events. Events from other people's private sessions are left out.",
50
+ inputSchema,
51
+ execute: async (input) => {
52
+ if (input.cursor && !decodeAuditAfterCursor(input.cursor)) throw new Error("That cursor is not one this tool returned.");
53
+ const since = input.since ? new Date(input.since) : void 0;
54
+ const until = input.until ? new Date(input.until) : void 0;
55
+ if (since && until && since >= until) throw new Error("`since` must be before `until`.");
56
+ if (input.includeAgentRuns && (!input.actor || input.actor.startsWith(AGENT_ACTOR_PREFIX))) throw new Error("`includeAgentRuns` needs a person as `actor`.");
57
+ let workItemId;
58
+ if (input.workItem) {
59
+ const item = await findWorkItem(deps.workItems, scope, input.workItem);
60
+ if (!item) throw workItemNotFound(input.workItem);
61
+ workItemId = item.id;
62
+ }
63
+ const namespaceActions = input.namespace ? auditActionsInNamespaces([input.namespace]) : void 0;
64
+ const actions = input.actions && namespaceActions ? input.actions.filter((action) => namespaceActions.includes(action)) : input.actions ?? namespaceActions;
65
+ if (actions && actions.length === 0) return { events: [] };
66
+ const actorId = input.actor === "me" ? scope.userId : input.actor;
67
+ const limit = input.limit ?? DEFAULT_LIMIT;
68
+ const visible = eventVisibility(scope, deps);
69
+ const events = [];
70
+ let before = input.cursor ?? (until ? auditCursorAt(until) : void 0);
71
+ const beforeUntil = (event) => !until || event.occurredAt < until;
72
+ for (let page = 0; page < MAX_PAGES; page++) {
73
+ const result = await deps.audit.list({
74
+ ...project,
75
+ ...actions ? { actions } : {},
76
+ ...actorId && !input.includeAgentRuns ? { actorId } : {},
77
+ ...before ? { before } : {},
78
+ limit: PAGE_SIZE
79
+ });
80
+ for (const event of result.events) {
81
+ if (since && event.occurredAt < since) return { events };
82
+ if (!beforeUntil(event)) continue;
83
+ if (actorId && event.actorId !== actorId && startedBy(event) !== actorId) continue;
84
+ if (workItemId && !event.targets.some((target) => target.type === "work_item" && target.id === workItemId)) continue;
85
+ if (!await visible(event)) continue;
86
+ events.push(summarize(event));
87
+ if (events.length === limit) return {
88
+ events,
89
+ nextCursor: encodeAuditCursor(event)
90
+ };
91
+ }
92
+ if (!result.nextCursor) return { events };
93
+ before = result.nextCursor;
94
+ }
95
+ return {
96
+ events,
97
+ nextCursor: before
98
+ };
99
+ }
100
+ });
101
+ }
102
+ function summarize(event) {
103
+ const name = actorName(event);
104
+ const runStartedBy = startedBy(event);
105
+ return {
106
+ action: event.action,
107
+ occurredAt: event.occurredAt.toISOString(),
108
+ actor: {
109
+ type: event.actorType,
110
+ id: event.actorId,
111
+ ...name ? { name } : {}
112
+ },
113
+ ...runStartedBy ? { startedBy: runStartedBy } : {},
114
+ targets: event.targets.slice(0, 10).map((target) => ({
115
+ type: target.type,
116
+ id: truncate(target.id, 600),
117
+ ...target.name ? { name: truncate(target.name, 600) } : {}
118
+ }))
119
+ };
120
+ }
121
+ /** Sessions an event names: its session targets and the session it records it acted in. */
122
+ function sessionRefs(event) {
123
+ const ids = event.targets.filter((target) => target.type === "session").map((target) => target.id);
124
+ const recorded = event.metadata?.sessionId;
125
+ if (typeof recorded === "string") ids.push(recorded);
126
+ return [...new Set(ids)];
127
+ }
128
+ /**
129
+ * Whether the caller may see an event. An event that names a session, or an
130
+ * agent's act (which belongs to the session it ran in), is only visible when
131
+ * every such session is shared or the caller's own. Fails closed when a
132
+ * session can't be found.
133
+ */
134
+ function eventVisibility(scope, deps) {
135
+ const sessions = /* @__PURE__ */ new Map();
136
+ const threads = /* @__PURE__ */ new Map();
137
+ let runAgents;
138
+ const sessionVisible = (sessionId) => {
139
+ let result = sessions.get(sessionId);
140
+ if (!result) {
141
+ result = (async () => {
142
+ const row = await deps.sessions?.getBySessionId(sessionId);
143
+ if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return false;
144
+ return row.visibility !== "private" || row.userId === scope.userId;
145
+ })().catch(() => false);
146
+ sessions.set(sessionId, result);
147
+ }
148
+ return result;
149
+ };
150
+ const threadVisible = async (threadId) => {
151
+ runAgents ??= deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId).then((bindings) => new Set(bindings.flatMap((binding) => [binding.threadId, binding.id])));
152
+ if ((await runAgents).has(threadId)) return true;
153
+ const controller = (await deps.messaging?.())?.controller;
154
+ if (!controller) return false;
155
+ const thread = await controller.queryThreadById({ threadId });
156
+ if (!thread) return false;
157
+ const stamped = thread.metadata?.factorySessionId;
158
+ return sessionVisible(typeof stamped === "string" ? stamped : thread.id);
159
+ };
160
+ const agentVisible = (event) => {
161
+ if (startedBy(event) === scope.userId) return true;
162
+ if (!event.actorId.startsWith(AGENT_ACTOR_PREFIX)) return false;
163
+ const threadId = event.actorId.slice(6);
164
+ let result = threads.get(threadId);
165
+ if (!result) {
166
+ const sessionId = threadId.startsWith(SESSION_ACTOR_PREFIX) ? threadId.slice(8) : void 0;
167
+ result = (sessionId ? sessionVisible(sessionId) : threadVisible(threadId)).catch(() => false);
168
+ threads.set(threadId, result);
169
+ }
170
+ return result;
171
+ };
172
+ return async (event) => {
173
+ if (event.actorType === "agent" && !await agentVisible(event)) return false;
174
+ for (const sessionId of sessionRefs(event)) if (!await sessionVisible(sessionId)) return false;
175
+ return true;
176
+ };
177
+ }
178
+ export { createAuditEventsTool };
179
+
180
+ //# sourceMappingURL=audit-events-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-events-tool.js","names":[],"sources":["../../src/tools/audit-events-tool.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { auditActionsInNamespaces, auditNamespaces, isAuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditNamespace } from '../storage/domains/audit/actions.js';\nimport {\n ACTOR_PROFILE_METADATA_KEY,\n auditCursorAt,\n decodeAuditAfterCursor,\n encodeAuditCursor,\n} from '../storage/domains/audit/base.js';\nimport type { AuditEventRow } from '../storage/domains/audit/base.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport { MAX_LIST, MAX_TEXT, findWorkItem, truncate, workItemNotFound, workItemRefSchema } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nconst DEFAULT_LIMIT = 25;\nconst PAGE_SIZE = 200;\n/** Pages read per call before handing back a cursor, so a narrow filter can't scan the whole trail at once. */\nconst MAX_PAGES = 5;\nconst AGENT_ACTOR_PREFIX = 'agent:';\nconst SESSION_ACTOR_PREFIX = 'session:';\n\nexport interface FactoryAuditToolDependencies {\n workItems: FactoryReadToolDependencies['workItems'];\n audit: FactoryReadToolDependencies['audit'];\n messaging?: FactoryReadToolDependencies['messaging'];\n /** Finds the sessions an event names or an agent ran in, to leave out other people's private sessions. */\n sessions?: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\nconst namespaces = auditNamespaces() as [AuditNamespace, ...AuditNamespace[]];\n\nconst inputSchema = z\n .object({\n actor: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('\"me\", a user id, or an agent actor id like \"agent:<threadId>\". Only events this actor performed.'),\n includeAgentRuns: z\n .boolean()\n .optional()\n .describe('With a person as `actor`: also include what agents did in runs that person started.'),\n namespace: z.enum(namespaces).optional().describe('Only actions in this namespace, e.g. \"work_item\" or \"run\".'),\n actions: z\n .array(z.string().refine(isAuditAction, { message: 'Not a Factory audit action.' }))\n .min(1)\n .max(50)\n .optional()\n .describe('Only these exact actions, e.g. [\"factory.work_item.stage_moved\"].'),\n workItem: workItemRefSchema.optional().describe('Only events that acted on this work item (id or \"#123\").'),\n since: z.iso.datetime({ offset: true }).optional().describe('Only events at or after this ISO time.'),\n until: z.iso.datetime({ offset: true }).optional().describe('Only events before this ISO time.'),\n cursor: z.string().min(1).max(200).optional().describe('`nextCursor` from a previous call, to read older events.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIMIT}, max ${MAX_LIST}.`),\n })\n .strict();\n\n/** A display name stamped at record time, or nothing when it is an email (the fallback when a person has no name). */\nfunction actorName(event: AuditEventRow): string | undefined {\n const profile = event.metadata?.[ACTOR_PROFILE_METADATA_KEY] as { name?: unknown } | undefined;\n const name = typeof profile?.name === 'string' ? profile.name.trim() : '';\n return name && !name.includes('@') ? truncate(name, MAX_TEXT) : undefined;\n}\n\nfunction startedBy(event: AuditEventRow): string | undefined {\n const value = event.metadata?.startedBy;\n return event.actorType === 'agent' && typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Who did what in this Factory, from its audit trail. The trail is org-wide and\n * its reads are unscoped by design, so this tool narrows what it hands back:\n * only this Factory's events, never request context (IP, user agent), names but\n * never emails, no metadata beyond what was acted on, and no events from or\n * about another person's private session.\n */\nexport function createAuditEventsTool(scope: FactoryToolScope, deps: FactoryAuditToolDependencies) {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n\n return createTool({\n id: 'factory_list_audit_events',\n description:\n 'List this Factory\\'s audit events, newest first: who did what to which work item, run, branch or setting, and when. Filter by actor (\"me\" or a user id, optionally with the agent runs they started), action namespace or exact actions, work item, and time range. Pass `nextCursor` back as `cursor` for older events. Events from other people\\'s private sessions are left out.',\n inputSchema,\n execute: async input => {\n if (input.cursor && !decodeAuditAfterCursor(input.cursor)) {\n throw new Error('That cursor is not one this tool returned.');\n }\n const since = input.since ? new Date(input.since) : undefined;\n const until = input.until ? new Date(input.until) : undefined;\n if (since && until && since >= until) throw new Error('`since` must be before `until`.');\n if (input.includeAgentRuns && (!input.actor || input.actor.startsWith(AGENT_ACTOR_PREFIX))) {\n throw new Error('`includeAgentRuns` needs a person as `actor`.');\n }\n\n let workItemId: string | undefined;\n if (input.workItem) {\n const item = await findWorkItem(deps.workItems, scope, input.workItem);\n if (!item) throw workItemNotFound(input.workItem);\n workItemId = item.id;\n }\n\n const namespaceActions = input.namespace ? auditActionsInNamespaces([input.namespace]) : undefined;\n const actions =\n input.actions && namespaceActions\n ? input.actions.filter(action => namespaceActions.includes(action))\n : (input.actions ?? namespaceActions);\n if (actions && actions.length === 0) return { events: [] };\n\n const actorId = input.actor === 'me' ? scope.userId : input.actor;\n const limit = input.limit ?? DEFAULT_LIMIT;\n const visible = eventVisibility(scope, deps);\n\n const events: ReturnType<typeof summarize>[] = [];\n let before = input.cursor ?? (until ? auditCursorAt(until) : undefined);\n // `auditCursorAt` sits after every row at that instant; `until` excludes them.\n const beforeUntil = (event: AuditEventRow) => !until || event.occurredAt < until;\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await deps.audit.list({\n ...project,\n ...(actions ? { actions } : {}),\n ...(actorId && !input.includeAgentRuns ? { actorId } : {}),\n ...(before ? { before } : {}),\n limit: PAGE_SIZE,\n });\n for (const event of result.events) {\n if (since && event.occurredAt < since) return { events };\n if (!beforeUntil(event)) continue;\n if (actorId && event.actorId !== actorId && startedBy(event) !== actorId) continue;\n if (workItemId && !event.targets.some(target => target.type === 'work_item' && target.id === workItemId)) {\n continue;\n }\n if (!(await visible(event))) continue;\n events.push(summarize(event));\n if (events.length === limit) return { events, nextCursor: encodeAuditCursor(event) };\n }\n if (!result.nextCursor) return { events };\n before = result.nextCursor;\n }\n // Scan budget spent: hand back where to pick up, even with fewer events than asked for.\n return { events, nextCursor: before };\n },\n });\n}\n\nfunction summarize(event: AuditEventRow) {\n const name = actorName(event);\n const runStartedBy = startedBy(event);\n return {\n action: event.action,\n occurredAt: event.occurredAt.toISOString(),\n actor: { type: event.actorType, id: event.actorId, ...(name ? { name } : {}) },\n ...(runStartedBy ? { startedBy: runStartedBy } : {}),\n targets: event.targets.slice(0, 10).map(target => ({\n type: target.type,\n id: truncate(target.id, MAX_TEXT),\n ...(target.name ? { name: truncate(target.name, MAX_TEXT) } : {}),\n })),\n };\n}\n\n/** Sessions an event names: its session targets and the session it records it acted in. */\nfunction sessionRefs(event: AuditEventRow): string[] {\n const ids = event.targets.filter(target => target.type === 'session').map(target => target.id);\n const recorded = event.metadata?.sessionId;\n if (typeof recorded === 'string') ids.push(recorded);\n return [...new Set(ids)];\n}\n\n/**\n * Whether the caller may see an event. An event that names a session, or an\n * agent's act (which belongs to the session it ran in), is only visible when\n * every such session is shared or the caller's own. Fails closed when a\n * session can't be found.\n */\nfunction eventVisibility(scope: FactoryToolScope, deps: FactoryAuditToolDependencies) {\n const sessions = new Map<string, Promise<boolean>>();\n const threads = new Map<string, Promise<boolean>>();\n let runAgents: Promise<Set<string>> | undefined;\n\n const sessionVisible = (sessionId: string): Promise<boolean> => {\n let result = sessions.get(sessionId);\n if (!result) {\n result = (async () => {\n const row = await deps.sessions?.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return false;\n return row.visibility !== 'private' || row.userId === scope.userId;\n })().catch(() => false);\n sessions.set(sessionId, result);\n }\n return result;\n };\n\n const threadVisible = async (threadId: string): Promise<boolean> => {\n // Work item runs are on the board for everyone in the Factory. A run's agent is recorded\n // under its thread (commits, pushes, signals) or under its binding (stage moves).\n runAgents ??= deps.workItems\n .listRunBindings(scope.orgId, scope.factoryProjectId)\n .then(bindings => new Set(bindings.flatMap(binding => [binding.threadId, binding.id])));\n if ((await runAgents).has(threadId)) return true;\n\n const controller = (await deps.messaging?.())?.controller;\n if (!controller) return false;\n const thread = await controller.queryThreadById({ threadId });\n if (!thread) return false;\n const stamped = thread.metadata?.factorySessionId;\n return sessionVisible(typeof stamped === 'string' ? stamped : thread.id);\n };\n\n const agentVisible = (event: AuditEventRow): Promise<boolean> | boolean => {\n if (startedBy(event) === scope.userId) return true;\n if (!event.actorId.startsWith(AGENT_ACTOR_PREFIX)) return false;\n const threadId = event.actorId.slice(AGENT_ACTOR_PREFIX.length);\n let result = threads.get(threadId);\n if (!result) {\n // Turns nobody signed in started are recorded as their session's agent: `agent:session:<sessionId>`.\n // Work item runs are created shared, so the session's own visibility decides.\n const sessionId = threadId.startsWith(SESSION_ACTOR_PREFIX)\n ? threadId.slice(SESSION_ACTOR_PREFIX.length)\n : undefined;\n result = (sessionId ? sessionVisible(sessionId) : threadVisible(threadId)).catch(() => false);\n threads.set(threadId, result);\n }\n return result;\n };\n\n return async (event: AuditEventRow): Promise<boolean> => {\n if (event.actorType === 'agent' && !(await agentVisible(event))) return false;\n for (const sessionId of sessionRefs(event)) {\n if (!(await sessionVisible(sessionId))) return false;\n }\n return true;\n };\n}\n"],"mappings":";;;;;;AAiBA,MAAM,gBAAgB;AACtB,MAAM,YAAY;;AAElB,MAAM,YAAY;AAClB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAU7B,MAAM,aAAa,gBAAgB;AAEnC,MAAM,cAAc,EACjB,OAAO;CACN,OAAO,EACJ,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAA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AM,cAAc,MAAM,KAAK,YAAY,EAAA,EAAI;EAC/C,IAAI,CAAC,YAAY,OAAO;EACxB,MAAM,SAAS,MAAM,WAAW,gBAAgB,EAAE,SAAS,CAAC;EAC5D,IAAI,CAAC,QAAQ,OAAO;EACpB,MAAM,UAAU,OAAO,UAAU;EACjC,OAAO,eAAe,OAAO,YAAY,WAAW,UAAU,OAAO,EAAE;CACzE;CAEA,MAAM,gBAAgB,UAAqD;EACzE,IAAI,UAAU,KAAK,MAAM,MAAM,QAAQ,OAAO;EAC9C,IAAI,CAAC,MAAM,QAAQ,WAAW,kBAAkB,GAAG,OAAO;EAC1D,MAAM,WAAW,MAAM,QAAQ,MAAM,CAAyB;EAC9D,IAAI,SAAS,QAAQ,IAAI,QAAQ;EACjC,IAAI,CAAC,QAAQ;GAGX,MAAM,YAAY,SAAS,WAAW,oBAAoB,IACtD,SAAS,MAAM,CAA2B,IAC1C,KAAA;GACJ,UAAU,YAAY,eAAe,SAAS,IAAI,cAAc,QAAQ,EAAA,CAAG,YAAY,KAAK;GAC5F,QAAQ,IAAI,UAAU,MAAM;EAC9B;EACA,OAAO;CACT;CAEA,OAAO,OAAO,UAA2C;EACvD,IAAI,MAAM,cAAc,WAAW,CAAE,MAAM,aAAa,KAAK,GAAI,OAAO;EACxE,KAAK,MAAM,aAAa,YAAY,KAAK,GACvC,IAAI,CAAE,MAAM,eAAe,SAAS,GAAI,OAAO;EAEjD,OAAO;CACT;AACF"}
@@ -1,5 +1,6 @@
1
1
  import type { IntegrationTools } from '../integrations/base.js';
2
2
  import type { FactoryApprovalToolDependencies } from './approval-tools.js';
3
+ import type { FactoryAuditToolDependencies } from './audit-events-tool.js';
3
4
  import type { FactoryMessagingToolDependencies } from './messaging-tools.js';
4
5
  import type { FactoryReadToolDependencies } from './read-tools.js';
5
6
  import type { FactoryToolScope } from './scope.js';
@@ -9,7 +10,7 @@ export { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './p
9
10
  export { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';
10
11
  export type { FactoryToolScope } from './scope.js';
11
12
  /** Storage and services the Factory tools act through. */
12
- export type FactoryToolDependencies = FactoryReadToolDependencies & FactoryWorkItemToolDependencies & FactoryMessagingToolDependencies & FactorySessionToolDependencies & FactoryApprovalToolDependencies;
13
+ export type FactoryToolDependencies = FactoryReadToolDependencies & FactoryAuditToolDependencies & FactoryWorkItemToolDependencies & FactoryMessagingToolDependencies & FactorySessionToolDependencies & FactoryApprovalToolDependencies;
13
14
  export interface CreateFactoryToolsOptions {
14
15
  scope: FactoryToolScope;
15
16
  deps: FactoryToolDependencies;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AAE3E,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AAEzE,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AAE5E,OAAO,EAAE,8BAA8B,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC/F,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC9E,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,0DAA0D;AAC1D,MAAM,MAAM,uBAAuB,GAAG,2BAA2B,GAC/D,+BAA+B,GAC/B,gCAAgC,GAChC,8BAA8B,GAC9B,+BAA+B,CAAC;AAElC,MAAM,W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,KAAK,EAAE,IAAI,EAAE,EAAE,yBAAyB,GAAG,gBAAgB,CAW/F"}
@@ -1,5 +1,6 @@
1
1
  import { FACTORY_INTERACTIVE_KEY } from "../auth.js";
2
2
  import { createFactoryApprovalTools } from "./approval-tools.js";
3
+ import { createAuditEventsTool } from "./audit-events-tool.js";
3
4
  import { createFactoryMessagingTools } from "./messaging-tools.js";
4
5
  import { createFactoryReadTools } from "./read-tools.js";
5
6
  import { createFactorySessionTools } from "./session-tools.js";
@@ -24,6 +25,7 @@ function createFactoryTools({ scope, deps }) {
24
25
  if (scope.kind !== "user") return messagingTools;
25
26
  return {
26
27
  ...createFactoryReadTools(scope, deps),
28
+ factory_list_audit_events: createAuditEventsTool(scope, deps),
27
29
  ...messagingTools,
28
30
  ...createFactoryWorkItemTools(scope, deps),
29
31
  ...createFactorySessionTools(scope, deps),
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals and muting\n * side sessions need a person, moves run as an agent, model switches reach\n * only this session and its side sessions, and starts are side sessions only.\n */\nexport function createFactoryTools({ scope, deps }: CreateFactoryToolsOptions): IntegrationTools {\n const messagingTools = createFactoryMessagingTools(scope, deps);\n if (scope.kind !== 'user') return messagingTools;\n return {\n ...createFactoryReadTools(scope, deps),\n ...messagingTools,\n ...createFactoryWorkItemTools(scope, deps),\n ...createFactorySessionTools(scope, deps),\n ...createFactoryApprovalTools(scope, deps),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,mBAAmB,EAAE,OAAO,QAAqD;CAC/F,MAAM,iBAAiB,4BAA4B,OAAO,IAAI;CAC9D,IAAI,MAAM,SAAS,QAAQ,OAAO;CAClC,OAAO;EACL,GAAG,uBAAuB,OAAO,IAAI;EACrC,GAAG;EACH,GAAG,2BAA2B,OAAO,IAAI;EACzC,GAAG,0BAA0B,OAAO,IAAI;EACxC,GAAG,2BAA2B,OAAO,IAAI;CAC3C;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/tools/index.ts"],"sourcesContent":["import type { IntegrationTools } from '../integrations/base.js';\nimport { createFactoryApprovalTools } from './approval-tools.js';\nimport type { FactoryApprovalToolDependencies } from './approval-tools.js';\nimport { createAuditEventsTool } from './audit-events-tool.js';\nimport type { FactoryAuditToolDependencies } from './audit-events-tool.js';\nimport { createFactoryMessagingTools } from './messaging-tools.js';\nimport type { FactoryMessagingToolDependencies } from './messaging-tools.js';\nimport { createFactoryReadTools } from './read-tools.js';\nimport type { FactoryReadToolDependencies } from './read-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { createFactorySessionTools } from './session-tools.js';\nimport type { FactorySessionToolDependencies } from './session-tools.js';\nimport { createFactoryWorkItemTools } from './work-item-tools.js';\nimport type { FactoryWorkItemToolDependencies } from './work-item-tools.js';\n\nexport { FACTORY_TOOLS_WITHOUT_APPROVAL, applyFactoryToolPermissions } from './permissions.js';\nexport { FACTORY_INTERACTIVE_KEY, resolveFactoryToolScope } from './scope.js';\nexport type { FactoryToolScope } from './scope.js';\n\n/** Storage and services the Factory tools act through. */\nexport type FactoryToolDependencies = FactoryReadToolDependencies &\n FactoryAuditToolDependencies &\n FactoryWorkItemToolDependencies &\n FactoryMessagingToolDependencies &\n FactorySessionToolDependencies &\n FactoryApprovalToolDependencies;\n\nexport interface CreateFactoryToolsOptions {\n scope: FactoryToolScope;\n deps: FactoryToolDependencies;\n}\n\n/**\n * The Factory toolset for a resolved scope. Tools take scope and storage by\n * closure and never read the request context, so a non-session transport\n * (an MCP server) can mount the same set with a scope it resolved itself.\n *\n * Worker and side sessions only answer messages. User sessions get every tool\n * on every turn. Turns nobody signed in started (notification wakes, webhooks,\n * dispatcher notices) carry text other people wrote, so each tool limits what\n * it does on them itself: approvals, proposals and muting\n * side sessions need a person, moves run as an agent, model switches reach\n * only this session and its side sessions, and starts are side sessions only.\n */\nexport function createFactoryTools({ scope, deps }: CreateFactoryToolsOptions): IntegrationTools {\n const messagingTools = createFactoryMessagingTools(scope, deps);\n if (scope.kind !== 'user') return messagingTools;\n return {\n ...createFactoryReadTools(scope, deps),\n factory_list_audit_events: createAuditEventsTool(scope, deps),\n ...messagingTools,\n ...createFactoryWorkItemTools(scope, deps),\n ...createFactorySessionTools(scope, deps),\n ...createFactoryApprovalTools(scope, deps),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,mBAA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":"","sources":["../../src/tools/permissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,EAAE,SAAS,MAAM,EAuB3D,CAAC;AAEF,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,CAAC,QAAQ,EAAE;QAAE,KAAK,IAAI,MAAM,CAAA;KAAE,CAAC;IACvC,QAAQ,CAAC,WAAW,EAAE;QACpB,QAAQ,IAAI,eAAe,CAAC;QAC5B,UAAU,CAAC,IAAI,EAAE;YAAE,QAAQ,EAAE,MAAM,CAAC;YAAC,MAAM,EAAE,gBAAgB,CAAA;SAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KACjF,CAAC;CACH;AAED,MAAM,WAAW,kCAAkC;IACjD,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;CAC9D;AAED;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,6BAA6B,EACtC,EAAE,QAAQ,EAAE,EAAE,kCAAkC,EAChD,SAAS,GAAE,SAAS,MAAM,EAAmC,GAC5D,OAAO,CAAC,IAAI,CAAC,CASf"}
@@ -8,6 +8,7 @@ const FACTORY_TOOLS_WITHOUT_APPROVAL = [
8
8
  "factory_list_work_items",
9
9
  "factory_inspect_work_item",
10
10
  "factory_list_attention",
11
+ "factory_list_audit_events",
11
12
  "factory_create_work_item",
12
13
  "factory_update_work_item",
13
14
  "factory_transition_work_item",
@@ -1 +1 @@
1
- {"version":3,"file":"permissions.js","names":[],"sources":["../../src/tools/permissions.ts"],"sourcesContent":["import type { PermissionPolicy, PermissionRules } from '@mastra/core/agent-controller';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\n\n/**\n * Factory tools that run without asking. Factory tools fall into the SDK's\n * `mcp` category, whose default policy is `ask`, so each of these needs an\n * explicit per-session `allow`.\n */\nexport const FACTORY_TOOLS_WITHOUT_APPROVAL: readonly string[] = [\n 'factory_list_work_items',\n 'factory_inspect_work_item',\n 'factory_list_attention',\n 'factory_create_work_item',\n 'factory_update_work_item',\n 'factory_transition_work_item',\n 'factory_retry_decision',\n 'factory_dismiss_decision',\n 'factory_resolve_proposal',\n 'factory_subscribe_work_item',\n 'factory_unsubscribe_work_item',\n 'factory_signal_session',\n 'factory_message_origin',\n 'factory_list_side_sessions',\n 'factory_subscribe_session',\n 'factory_unsubscribe_session',\n 'factory_start_session',\n 'factory_answer_approval',\n 'factory_switch_session_model',\n 'factory_recreate_sandbox',\n 'factory_sandbox_port_url',\n];\n\nexport interface FactoryToolPermissionsSession {\n readonly identity: { getId(): string };\n readonly permissions: {\n getRules(): PermissionRules;\n setForTool(args: { toolName: string; policy: PermissionPolicy }): Promise<void>;\n };\n}\n\nexport interface FactoryToolPermissionsDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\n/**\n * Allow the no-approval Factory tools on a newly created Factory session.\n * This only sets policy; which tools a turn actually gets is decided by the\n * tool scope. A person's own choices win: a per-tool policy is never\n * overwritten, and an explicit `mcp` category policy leaves everything alone.\n */\nexport async function applyFactoryToolPermissions(\n session: FactoryToolPermissionsSession,\n { sessions }: FactoryToolPermissionsDependencies,\n toolNames: readonly string[] = FACTORY_TOOLS_WITHOUT_APPROVAL,\n): Promise<void> {\n const row = await sessions.getBySessionId(session.identity.getId());\n if (!row?.factoryProjectId) return;\n const rules = session.permissions.getRules();\n if (rules.categories.mcp !== undefined) return;\n for (const toolName of toolNames) {\n if (session.permissions.getRules().tools[toolName] !== undefined) continue;\n await session.permissions.setForTool({ toolName, policy: 'allow' });\n }\n}\n"],"mappings":";;;;;;AASA,MAAa,iCAAoD;CAC/D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAoBA,eAAsB,4BACpB,SACA,EAAE,YACF,YAA+B,gCAChB;CAEf,IAAI,EAAC,MADa,SAAS,eAAe,QAAQ,SAAS,MAAM,CAAC,EAAA,EACxD,kBAAkB;CAE5B,IADc,QAAQ,YAAY,SAC1B,CAAC,CAAC,WAAW,QAAQ,KAAA,GAAW;CACxC,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,QAAQ,YAAY,SAAS,CAAC,CAAC,MAAM,cAAc,KAAA,GAAW;EAClE,MAAM,QAAQ,YAAY,WAAW;GAAE;GAAU,QAAQ;EAAQ,CAAC;CACpE;AACF"}
1
+ {"version":3,"file":"permissions.js","names":[],"sources":["../../src/tools/permissions.ts"],"sourcesContent":["import type { PermissionPolicy, PermissionRules } from '@mastra/core/agent-controller';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\n\n/**\n * Factory tools that run without asking. Factory tools fall into the SDK's\n * `mcp` category, whose default policy is `ask`, so each of these needs an\n * explicit per-session `allow`.\n */\nexport const FACTORY_TOOLS_WITHOUT_APPROVAL: readonly string[] = [\n 'factory_list_work_items',\n 'factory_inspect_work_item',\n 'factory_list_attention',\n 'factory_list_audit_events',\n 'factory_create_work_item',\n 'factory_update_work_item',\n 'factory_transition_work_item',\n 'factory_retry_decision',\n 'factory_dismiss_decision',\n 'factory_resolve_proposal',\n 'factory_subscribe_work_item',\n 'factory_unsubscribe_work_item',\n 'factory_signal_session',\n 'factory_message_origin',\n 'factory_list_side_sessions',\n 'factory_subscribe_session',\n 'factory_unsubscribe_session',\n 'factory_start_session',\n 'factory_answer_approval',\n 'factory_switch_session_model',\n 'factory_recreate_sandbox',\n 'factory_sandbox_port_url',\n];\n\nexport interface FactoryToolPermissionsSession {\n readonly identity: { getId(): string };\n readonly permissions: {\n getRules(): PermissionRules;\n setForTool(args: { toolName: string; policy: PermissionPolicy }): Promise<void>;\n };\n}\n\nexport interface FactoryToolPermissionsDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n}\n\n/**\n * Allow the no-approval Factory tools on a newly created Factory session.\n * This only sets policy; which tools a turn actually gets is decided by the\n * tool scope. A person's own choices win: a per-tool policy is never\n * overwritten, and an explicit `mcp` category policy leaves everything alone.\n */\nexport async function applyFactoryToolPermissions(\n session: FactoryToolPermissionsSession,\n { sessions }: FactoryToolPermissionsDependencies,\n toolNames: readonly string[] = FACTORY_TOOLS_WITHOUT_APPROVAL,\n): Promise<void> {\n const row = await sessions.getBySessionId(session.identity.getId());\n if (!row?.factoryProjectId) return;\n const rules = session.permissions.getRules();\n if (rules.categories.mcp !== undefined) return;\n for (const toolName of toolNames) {\n if (session.permissions.getRules().tools[toolName] !== undefined) continue;\n await session.permissions.setForTool({ toolName, policy: 'allow' });\n }\n}\n"],"mappings":";;;;;;AASA,MAAa,iCAAoD;CAC/D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAoBA,eAAsB,4BACpB,SACA,EAAE,YACF,YAA+B,gCAChB;CAEf,IAAI,EAAC,MADa,SAAS,eAAe,QAAQ,SAAS,MAAM,CAAC,EAAA,EACxD,kBAAkB;CAE5B,IADc,QAAQ,YAAY,SAC1B,CAAC,CAAC,WAAW,QAAQ,KAAA,GAAW;CACxC,KAAK,MAAM,YAAY,WAAW;EAChC,IAAI,QAAQ,YAAY,SAAS,CAAC,CAAC,MAAM,cAAc,KAAA,GAAW;EAClE,MAAM,QAAQ,YAAY,WAAW;GAAE;GAAU,QAAQ;EAAQ,CAAC;CACpE;AACF"}
@@ -87,12 +87,12 @@ var FactorySessionsStateProcessor = class {
87
87
  sessionId: scope.sessionId
88
88
  });
89
89
  if (!binding) return null;
90
- const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);
91
90
  const following = (await this.#deps.workItems.listWorkItemSubscribers({
92
91
  orgId: scope.orgId,
93
92
  workItemId: binding.workItemId
94
93
  })).filter((subscriber) => subscriber.sessionId !== scope.sessionId).length;
95
94
  if (following === 0) return null;
95
+ const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);
96
96
  return `Working on ${item ? itemLabel(item) : binding.workItemId} as ${binding.role}. Reports go to ${following} following session${following === 1 ? "" : "s"}. ${PROGRESS_ASK}`;
97
97
  }
98
98
  async #userState(scope) {
@@ -1 +1 @@
1
- {"version":3,"file":"sessions-state-processor.js","names":["newest","report"],"sources":["../../src/tools/sessions-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { NotificationsStorage } from '@mastra/core/notifications';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryToolScope } from './scope.js';\nimport type { FactoryToolScope, ResolveFactoryToolScopeOptions } from './scope.js';\nimport {\n itemLabel,\n lastReport as report,\n listSessionNotifications,\n listSideSessions,\n newestNotification as newest,\n} from './side-sessions.js';\nimport type { FactorySessionRunState, LastReport } from './side-sessions.js';\n\nconst STATE_ID = 'factory-sessions';\n/** Finished side sessions and items that reached a terminal stage drop out after this long. */\nexport const FACTORY_SESSIONS_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n/** Asks a long run to show it is still moving; a silent half hour reads the same as a stuck one. */\nconst PROGRESS_ASK = 'On long work, send a progress report after each plan step.';\n\n/** A running worker whose thread has not moved for this long is shown as quiet, so a stuck run stands out. */\nexport const FACTORY_SESSIONS_QUIET_MS = 10 * 60 * 1000;\n/** Rows shown before the rest collapse into \"+N more\". */\nexport const FACTORY_SESSIONS_MAX_ROWS = 20;\nconst EMPTY_CACHE_KEY = 'empty';\n\nexport type { FactorySessionRunState } from './side-sessions.js';\n\nexport interface FactorySessionsStateDependencies {\n authEnabled: boolean;\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'listByOrigin'>;\n projects: ResolveFactoryToolScopeOptions['projects'];\n workItems: Pick<\n WorkItemsStorage,\n | 'hasRunBindingForSession'\n | 'listSessionSubscriptions'\n | 'getForProject'\n | 'listByIds'\n | 'listRunBindings'\n | 'findActiveRunBindingForSession'\n | 'listWorkItemSubscribers'\n >;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** Whether the session's agent is mid-run in this process; `idle` when it isn't live here. */\n isRunning: (sessionId: string) => Promise<boolean>;\n /** Whether the session is parked on a tool prompt; a parked run is still in flight but waits on a person. */\n isParked?: (sessionId: string) => boolean;\n /** When a thread last changed; tells a long run that is still moving from one that stopped. */\n lastActivity?: (threadId: string) => Promise<Date | null>;\n notifications: () => Promise<Pick<NotificationsStorage, 'listNotifications'> | null>;\n now?: () => number;\n}\n\ninterface SideSessionRow {\n sessionId: string;\n title: string;\n state: FactorySessionRunState;\n lastReport: LastReport | null;\n muted: boolean;\n}\n\ninterface FollowedRow {\n workItemId: string;\n label: string;\n title: string;\n stage: string;\n worker: { role: string; sessionId: string; state: FactorySessionRunState; quietSince: string | null } | null;\n lastReport: LastReport | null;\n}\n\ninterface SessionsState {\n sideSessions: SideSessionRow[];\n following: FollowedRow[];\n more: number;\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction cacheKeyFor(value: unknown): string {\n return `sessions:${createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * The `<factory-sessions>` state signal. A user session sees the side sessions\n * it started and the work items it follows; a side session or item worker sees\n * who it reports to. Sessions it only messaged never appear. Silent until there\n * is something to show; when the last entry ages out it sends one final empty\n * snapshot, then stays silent.\n */\nexport class FactorySessionsStateProcessor implements Processor<'factory-sessions'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n readonly #deps: FactorySessionsStateDependencies;\n\n constructor(deps: FactorySessionsStateDependencies) {\n this.#deps = deps;\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const scope = await resolveFactoryToolScope({\n requestContext: args.requestContext!,\n authEnabled: this.#deps.authEnabled,\n sessions: this.#deps.sessions,\n projects: this.#deps.projects,\n workItems: this.#deps.workItems,\n });\n if (!scope) return;\n\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n const previousKey = hasBase\n ? (args.tracking?.currentCacheKey ?? (args.lastSnapshot?.metadata?.state as { cacheKey?: string })?.cacheKey)\n : undefined;\n const unchanged = (cacheKey: string) => previousKey === cacheKey;\n // Silence rule: one final empty snapshot replaces a non-empty one, then nothing.\n const cleared = () => hasBase && previousKey !== undefined && previousKey !== EMPTY_CACHE_KEY;\n\n if (scope.kind === 'worker') {\n const contents = await this.#workerLine(scope);\n if (!contents) {\n return cleared()\n ? this.#signal(EMPTY_CACHE_KEY, 'This session is not reporting on any work now.', {}, { entries: 0 })\n : undefined;\n }\n const cacheKey = cacheKeyFor(contents);\n if (unchanged(cacheKey)) return;\n return this.#signal(cacheKey, escapeText(contents), { worker: contents }, { entries: 1 });\n }\n\n const state = await this.#userState(scope);\n if (state.sideSessions.length === 0 && state.following.length === 0) {\n if (!cleared()) return;\n return this.#signal(EMPTY_CACHE_KEY, 'No sub-sessions or followed work items.', state, { entries: 0 });\n }\n const cacheKey = cacheKeyFor(state);\n if (unchanged(cacheKey)) return;\n return this.#signal(cacheKey, this.#render(state), state, {\n sideSessions: state.sideSessions.length,\n following: state.following.length,\n });\n }\n\n #signal(cacheKey: string, contents: string, value: unknown, attributes: Record<string, number>) {\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot' as const,\n tagName: 'factory-sessions',\n contents,\n value: { sessions: value },\n attributes,\n metadata: { value: { sessions: value } },\n };\n }\n\n async #workerLine(scope: FactoryToolScope): Promise<string | null> {\n if (scope.origin) {\n return `Started by session ${scope.origin.sessionId} (thread ${scope.origin.threadId}). Report back with factory_message_origin. ${PROGRESS_ASK}`;\n }\n const binding = await this.#deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n if (!binding) return null;\n const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);\n const subscribers = await this.#deps.workItems.listWorkItemSubscribers({\n orgId: scope.orgId,\n workItemId: binding.workItemId,\n });\n const following = subscribers.filter(subscriber => subscriber.sessionId !== scope.sessionId).length;\n // Nobody to report to: nothing worth showing (most board-started workers).\n if (following === 0) return null;\n const label = item ? itemLabel(item) : binding.workItemId;\n return `Working on ${label} as ${binding.role}. Reports go to ${following} following session${following === 1 ? '' : 's'}. ${PROGRESS_ASK}`;\n }\n\n async #userState(scope: FactoryToolScope): Promise<SessionsState> {\n const now = this.#deps.now?.() ?? Date.now();\n const notifications = await this.#deps.notifications();\n const records = await listSessionNotifications(notifications, scope.threadId);\n\n const sideSessions: Array<SideSessionRow & { active: boolean }> = [];\n const listed = await listSideSessions(\n {\n sessions: this.#deps.sessions,\n workItems: this.#deps.workItems,\n isRunning: this.#deps.isRunning,\n isParked: this.#deps.isParked,\n notifications,\n },\n scope,\n { records },\n );\n for (const row of listed) {\n if (row.state !== 'running' && now - Date.parse(row.lastActivityAt) > FACTORY_SESSIONS_MAX_AGE_MS) continue;\n sideSessions.push({\n sessionId: row.sessionId,\n title: row.title,\n state: row.state,\n lastReport: row.lastReport,\n muted: row.mutedAt !== null,\n active: row.state !== 'idle',\n });\n }\n\n const subscriptions = await this.#deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n const workItemIds = subscriptions.map(subscription => subscription.workItemId);\n const [items, bindings] = await Promise.all([\n this.#deps.workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: workItemIds,\n }),\n this.#deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, workItemIds),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const following: Array<FollowedRow & { active: boolean }> = [];\n for (const subscription of subscriptions) {\n const item = itemsById.get(subscription.workItemId);\n if (!item) continue;\n const stage = item.stages[0] ?? 'unknown';\n const boards = await toBoardSource(this.#deps.boards).load(scope);\n const terminal = boards.get(boardForWorkItem(item))?.isTerminal(stage) ?? false;\n if (terminal && now - item.updatedAt.getTime() > FACTORY_SESSIONS_MAX_AGE_MS) continue;\n const active = bindings.find(binding => binding.workItemId === item.id && binding.status === 'active');\n const label = itemLabel(item);\n const last = newest(\n records,\n record =>\n record.attributes?.['work-item'] === label || (record.kind === 'stage' && record.sourceId === item.id),\n );\n const running = active ? await this.#deps.isRunning(active.sessionId) : false;\n // A run parked on a prompt is still in flight but waits on a person, so it reads as parked, never quiet.\n const parked = active ? Boolean(this.#deps.isParked?.(active.sessionId)) : false;\n const lastActivity = active && running && !parked ? await this.#deps.lastActivity?.(active.threadId) : null;\n // Only a quiet run is shown with its time; a moving one would change the snapshot on every step.\n const quiet = lastActivity && now - lastActivity.getTime() >= FACTORY_SESSIONS_QUIET_MS ? lastActivity : null;\n const lastFromWorker = active\n ? newest(records, record => record.attributes?.['from-session'] === active.sessionId)\n : undefined;\n following.push({\n workItemId: item.id,\n label,\n title: item.title,\n stage,\n worker: active\n ? {\n role: active.role,\n sessionId: active.sessionId,\n state:\n parked || (!running && lastFromWorker?.kind === 'blocked') ? 'parked' : running ? 'running' : 'idle',\n quietSince: quiet ? quiet.toISOString() : null,\n }\n : null,\n lastReport: report(last),\n active: running && !terminal,\n });\n }\n\n // Active entries first, then within the cap; the rest collapse into \"+N more\".\n const ordered = [\n ...sideSessions.map(row => ({ section: 'side' as const, row })),\n ...following.map(row => ({ section: 'following' as const, row })),\n ].sort((a, b) => Number(b.row.active) - Number(a.row.active));\n const shown = ordered.slice(0, FACTORY_SESSIONS_MAX_ROWS);\n const strip = <T extends { active: boolean }>({ active: _active, ...row }: T) => row;\n return {\n sideSessions: shown.flatMap(entry =>\n entry.section === 'side' ? [strip(entry.row as SideSessionRow & { active: boolean })] : [],\n ),\n following: shown.flatMap(entry =>\n entry.section === 'following' ? [strip(entry.row as FollowedRow & { active: boolean })] : [],\n ),\n more: ordered.length - shown.length,\n };\n }\n\n #render(state: SessionsState): string {\n const lastReport = (last: LastReport | null) => (last ? `; last report ${last.kind} at ${last.at}` : '');\n const lines: string[] = [];\n if (state.sideSessions.length > 0) {\n lines.push('Side sessions you started:');\n for (const row of state.sideSessions) {\n lines.push(\n `- \"${escapeText(row.title)}\" (session ${row.sessionId}): ${row.state}${row.muted ? ' (muted)' : ''}${lastReport(row.lastReport)}`,\n );\n }\n }\n if (state.following.length > 0) {\n lines.push('Work items you follow:');\n for (const row of state.following) {\n const worker = row.worker\n ? `; ${escapeText(row.worker.role)} session ${row.worker.sessionId} ${row.worker.state}${row.worker.quietSince ? ` but quiet since ${row.worker.quietSince}` : ''}`\n : '';\n lines.push(\n `- ${escapeText(row.label)} \"${escapeText(row.title)}\": ${escapeText(row.stage)}${worker}${lastReport(row.lastReport)}`,\n );\n }\n }\n if (state.more > 0) lines.push(`+${state.more} more`);\n lines.push(\n 'Message any of these sessions with factory_signal_session; read full reports with notification_inbox; list side sessions with factory_list_side_sessions; on a turn a person started, mute one with factory_unsubscribe_session.',\n );\n return lines.join('\\n');\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,WAAW;;AAEjB,MAAa,8BAA8B;;AAE3C,MAAM,eAAe;;AAGrB,MAAa,4BAA4B;;AAEzC,MAAa,4BAA4B;AACzC,MAAM,kBAAkB;AAqDxB,SAAS,WAAW,OAAuB;CACzC,OAAO,MAAM,WAAW,KAAK,OAAO,CAAC,CAAC,WAAW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AM,KAAK,MAAM;EACpD,MAAM,KACJ,kOACF;EACA,OAAO,MAAM,KAAK,IAAI;CACxB;AACF"}
1
+ {"version":3,"file":"sessions-state-processor.js","names":["newest","report"],"sources":["../../src/tools/sessions-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { NotificationsStorage } from '@mastra/core/notifications';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryToolScope } from './scope.js';\nimport type { FactoryToolScope, ResolveFactoryToolScopeOptions } from './scope.js';\nimport {\n itemLabel,\n lastReport as report,\n listSessionNotifications,\n listSideSessions,\n newestNotification as newest,\n} from './side-sessions.js';\nimport type { FactorySessionRunState, LastReport } from './side-sessions.js';\n\nconst STATE_ID = 'factory-sessions';\n/** Finished side sessions and items that reached a terminal stage drop out after this long. */\nexport const FACTORY_SESSIONS_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n/** Asks a long run to show it is still moving; a silent half hour reads the same as a stuck one. */\nconst PROGRESS_ASK = 'On long work, send a progress report after each plan step.';\n\n/** A running worker whose thread has not moved for this long is shown as quiet, so a stuck run stands out. */\nexport const FACTORY_SESSIONS_QUIET_MS = 10 * 60 * 1000;\n/** Rows shown before the rest collapse into \"+N more\". */\nexport const FACTORY_SESSIONS_MAX_ROWS = 20;\nconst EMPTY_CACHE_KEY = 'empty';\n\nexport type { FactorySessionRunState } from './side-sessions.js';\n\nexport interface FactorySessionsStateDependencies {\n authEnabled: boolean;\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'listByOrigin'>;\n projects: ResolveFactoryToolScopeOptions['projects'];\n workItems: Pick<\n WorkItemsStorage,\n | 'hasRunBindingForSession'\n | 'listSessionSubscriptions'\n | 'getForProject'\n | 'listByIds'\n | 'listRunBindings'\n | 'findActiveRunBindingForSession'\n | 'listWorkItemSubscribers'\n >;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** Whether the session's agent is mid-run in this process; `idle` when it isn't live here. */\n isRunning: (sessionId: string) => Promise<boolean>;\n /** Whether the session is parked on a tool prompt; a parked run is still in flight but waits on a person. */\n isParked?: (sessionId: string) => boolean;\n /** When a thread last changed; tells a long run that is still moving from one that stopped. */\n lastActivity?: (threadId: string) => Promise<Date | null>;\n notifications: () => Promise<Pick<NotificationsStorage, 'listNotifications'> | null>;\n now?: () => number;\n}\n\ninterface SideSessionRow {\n sessionId: string;\n title: string;\n state: FactorySessionRunState;\n lastReport: LastReport | null;\n muted: boolean;\n}\n\ninterface FollowedRow {\n workItemId: string;\n label: string;\n title: string;\n stage: string;\n worker: { role: string; sessionId: string; state: FactorySessionRunState; quietSince: string | null } | null;\n lastReport: LastReport | null;\n}\n\ninterface SessionsState {\n sideSessions: SideSessionRow[];\n following: FollowedRow[];\n more: number;\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction cacheKeyFor(value: unknown): string {\n return `sessions:${createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * The `<factory-sessions>` state signal. A user session sees the side sessions\n * it started and the work items it follows; a side session or item worker sees\n * who it reports to. Sessions it only messaged never appear. Silent until there\n * is something to show; when the last entry ages out it sends one final empty\n * snapshot, then stays silent.\n */\nexport class FactorySessionsStateProcessor implements Processor<'factory-sessions'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n readonly #deps: FactorySessionsStateDependencies;\n\n constructor(deps: FactorySessionsStateDependencies) {\n this.#deps = deps;\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const scope = await resolveFactoryToolScope({\n requestContext: args.requestContext!,\n authEnabled: this.#deps.authEnabled,\n sessions: this.#deps.sessions,\n projects: this.#deps.projects,\n workItems: this.#deps.workItems,\n });\n if (!scope) return;\n\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n const previousKey = hasBase\n ? (args.tracking?.currentCacheKey ?? (args.lastSnapshot?.metadata?.state as { cacheKey?: string })?.cacheKey)\n : undefined;\n const unchanged = (cacheKey: string) => previousKey === cacheKey;\n // Silence rule: one final empty snapshot replaces a non-empty one, then nothing.\n const cleared = () => hasBase && previousKey !== undefined && previousKey !== EMPTY_CACHE_KEY;\n\n if (scope.kind === 'worker') {\n const contents = await this.#workerLine(scope);\n if (!contents) {\n return cleared()\n ? this.#signal(EMPTY_CACHE_KEY, 'This session is not reporting on any work now.', {}, { entries: 0 })\n : undefined;\n }\n const cacheKey = cacheKeyFor(contents);\n if (unchanged(cacheKey)) return;\n return this.#signal(cacheKey, escapeText(contents), { worker: contents }, { entries: 1 });\n }\n\n const state = await this.#userState(scope);\n if (state.sideSessions.length === 0 && state.following.length === 0) {\n if (!cleared()) return;\n return this.#signal(EMPTY_CACHE_KEY, 'No sub-sessions or followed work items.', state, { entries: 0 });\n }\n const cacheKey = cacheKeyFor(state);\n if (unchanged(cacheKey)) return;\n return this.#signal(cacheKey, this.#render(state), state, {\n sideSessions: state.sideSessions.length,\n following: state.following.length,\n });\n }\n\n #signal(cacheKey: string, contents: string, value: unknown, attributes: Record<string, number>) {\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot' as const,\n tagName: 'factory-sessions',\n contents,\n value: { sessions: value },\n attributes,\n metadata: { value: { sessions: value } },\n };\n }\n\n async #workerLine(scope: FactoryToolScope): Promise<string | null> {\n if (scope.origin) {\n return `Started by session ${scope.origin.sessionId} (thread ${scope.origin.threadId}). Report back with factory_message_origin. ${PROGRESS_ASK}`;\n }\n const binding = await this.#deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n if (!binding) return null;\n const subscribers = await this.#deps.workItems.listWorkItemSubscribers({\n orgId: scope.orgId,\n workItemId: binding.workItemId,\n });\n const following = subscribers.filter(subscriber => subscriber.sessionId !== scope.sessionId).length;\n // Nobody to report to: nothing worth showing (most board-started workers), so skip the card read.\n if (following === 0) return null;\n const item = await this.#deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, binding.workItemId);\n const label = item ? itemLabel(item) : binding.workItemId;\n return `Working on ${label} as ${binding.role}. Reports go to ${following} following session${following === 1 ? '' : 's'}. ${PROGRESS_ASK}`;\n }\n\n async #userState(scope: FactoryToolScope): Promise<SessionsState> {\n const now = this.#deps.now?.() ?? Date.now();\n const notifications = await this.#deps.notifications();\n const records = await listSessionNotifications(notifications, scope.threadId);\n\n const sideSessions: Array<SideSessionRow & { active: boolean }> = [];\n const listed = await listSideSessions(\n {\n sessions: this.#deps.sessions,\n workItems: this.#deps.workItems,\n isRunning: this.#deps.isRunning,\n isParked: this.#deps.isParked,\n notifications,\n },\n scope,\n { records },\n );\n for (const row of listed) {\n if (row.state !== 'running' && now - Date.parse(row.lastActivityAt) > FACTORY_SESSIONS_MAX_AGE_MS) continue;\n sideSessions.push({\n sessionId: row.sessionId,\n title: row.title,\n state: row.state,\n lastReport: row.lastReport,\n muted: row.mutedAt !== null,\n active: row.state !== 'idle',\n });\n }\n\n const subscriptions = await this.#deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n const workItemIds = subscriptions.map(subscription => subscription.workItemId);\n const [items, bindings] = await Promise.all([\n this.#deps.workItems.listByIds({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n ids: workItemIds,\n }),\n this.#deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, workItemIds),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const following: Array<FollowedRow & { active: boolean }> = [];\n for (const subscription of subscriptions) {\n const item = itemsById.get(subscription.workItemId);\n if (!item) continue;\n const stage = item.stages[0] ?? 'unknown';\n const boards = await toBoardSource(this.#deps.boards).load(scope);\n const terminal = boards.get(boardForWorkItem(item))?.isTerminal(stage) ?? false;\n if (terminal && now - item.updatedAt.getTime() > FACTORY_SESSIONS_MAX_AGE_MS) continue;\n const active = bindings.find(binding => binding.workItemId === item.id && binding.status === 'active');\n const label = itemLabel(item);\n const last = newest(\n records,\n record =>\n record.attributes?.['work-item'] === label || (record.kind === 'stage' && record.sourceId === item.id),\n );\n const running = active ? await this.#deps.isRunning(active.sessionId) : false;\n // A run parked on a prompt is still in flight but waits on a person, so it reads as parked, never quiet.\n const parked = active ? Boolean(this.#deps.isParked?.(active.sessionId)) : false;\n const lastActivity = active && running && !parked ? await this.#deps.lastActivity?.(active.threadId) : null;\n // Only a quiet run is shown with its time; a moving one would change the snapshot on every step.\n const quiet = lastActivity && now - lastActivity.getTime() >= FACTORY_SESSIONS_QUIET_MS ? lastActivity : null;\n const lastFromWorker = active\n ? newest(records, record => record.attributes?.['from-session'] === active.sessionId)\n : undefined;\n following.push({\n workItemId: item.id,\n label,\n title: item.title,\n stage,\n worker: active\n ? {\n role: active.role,\n sessionId: active.sessionId,\n state:\n parked || (!running && lastFromWorker?.kind === 'blocked') ? 'parked' : running ? 'running' : 'idle',\n quietSince: quiet ? quiet.toISOString() : null,\n }\n : null,\n lastReport: report(last),\n active: running && !terminal,\n });\n }\n\n // Active entries first, then within the cap; the rest collapse into \"+N more\".\n const ordered = [\n ...sideSessions.map(row => ({ section: 'side' as const, row })),\n ...following.map(row => ({ section: 'following' as const, row })),\n ].sort((a, b) => Number(b.row.active) - Number(a.row.active));\n const shown = ordered.slice(0, FACTORY_SESSIONS_MAX_ROWS);\n const strip = <T extends { active: boolean }>({ active: _active, ...row }: T) => row;\n return {\n sideSessions: shown.flatMap(entry =>\n entry.section === 'side' ? [strip(entry.row as SideSessionRow & { active: boolean })] : [],\n ),\n following: shown.flatMap(entry =>\n entry.section === 'following' ? [strip(entry.row as FollowedRow & { active: boolean })] : [],\n ),\n more: ordered.length - shown.length,\n };\n }\n\n #render(state: SessionsState): string {\n const lastReport = (last: LastReport | null) => (last ? `; last report ${last.kind} at ${last.at}` : '');\n const lines: string[] = [];\n if (state.sideSessions.length > 0) {\n lines.push('Side sessions you started:');\n for (const row of state.sideSessions) {\n lines.push(\n `- \"${escapeText(row.title)}\" (session ${row.sessionId}): ${row.state}${row.muted ? ' (muted)' : ''}${lastReport(row.lastReport)}`,\n );\n }\n }\n if (state.following.length > 0) {\n lines.push('Work items you follow:');\n for (const row of state.following) {\n const worker = row.worker\n ? `; ${escapeText(row.worker.role)} session ${row.worker.sessionId} ${row.worker.state}${row.worker.quietSince ? ` but quiet since ${row.worker.quietSince}` : ''}`\n : '';\n lines.push(\n `- ${escapeText(row.label)} \"${escapeText(row.title)}\": ${escapeText(row.stage)}${worker}${lastReport(row.lastReport)}`,\n );\n }\n }\n if (state.more > 0) lines.push(`+${state.more} more`);\n lines.push(\n 'Message any of these sessions with factory_signal_session; read full reports with notification_inbox; list side sessions with factory_list_side_sessions; on a turn a person started, mute one with factory_unsubscribe_session.',\n );\n return lines.join('\\n');\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,WAAW;;AAEjB,MAAa,8BAA8B;;AAE3C,MAAM,eAAe;;AAGrB,MAAa,4BAA4B;;AAEzC,MAAa,4BAA4B;AACzC,MAAM,kBAAkB;AAqDxB,SAAS,WAAW,OAAuB;CACzC,OAAO,MAAM,WAAW,KAAK,OAAO,CAAC,CAAC,WAAW,KAAK,MAAM,CAAC,CAAC,WAAW,KAAK,MAAM;AACtF;AAEA,SAAS,YAAY,OAAwB;CAC3C,OAAO,YAAY,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AACjG;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B,MAAM,YAAY,SAAS,CAAC,MAAM,MAAM,GAA2C,CAAC,IAAI,CAAC,CAC3F;GACA,WAAW,MAAM,SAAQ,UACvB,MAAM,YAAY,cAAc,CAAC,MAAM,MAAM,GAAwC,CAAC,IAAI,CAAC,CAC7F;GACA,MAAM,QAAQ,SAAS,MAAM;EAC/B;CACF;CAEA,QAAQ,OAA8B;EACpC,MAAM,cAAc,SAA6B,OAAO,iBAAiB,KAAK,KAAK,MAAM,KAAK,OAAO;EACrG,MAAM,QAAkB,CAAC;EACzB,IAAI,MAAM,aAAa,SAAS,GAAG;GACjC,MAAM,KAAK,4BAA4B;GACvC,KAAK,MAAM,OAAO,MAAM,cACtB,MAAM,KACJ,MAAM,WAAW,IAAI,KAAK,EAAE,aAAa,IAAI,UAAU,KAAK,IAAI,QAAQ,IAAI,QAAQ,aAAa,KAAK,WAAW,IAAI,UAAU,GACjI;EAEJ;EACA,IAAI,MAAM,UAAU,SAAS,GAAG;GAC9B,MAAM,KAAK,wBAAwB;GACnC,KAAK,MAAM,OAAO,MAAM,WAAW;IACjC,MAAM,SAAS,IAAI,SACf,KAAK,WAAW,IAAI,OAAO,IAAI,EAAE,WAAW,IAAI,OAAO,UAAU,GAAG,IAAI,OAAO,QAAQ,IAAI,OAAO,aAAa,oBAAoB,IAAI,OAAO,eAAe,OAC7J;IACJ,MAAM,KACJ,KAAK,WAAW,IAAI,KAAK,EAAE,IAAI,WAAW,IAAI,KAAK,EAAE,KAAK,WAAW,IAAI,KAAK,IAAI,SAAS,WAAW,IAAI,UAAU,GACtH;GACF;EACF;EACA,IAAI,MAAM,OAAO,GAAG,MAAM,KAAK,IAAI,MAAM,KAAK,MAAM;EACpD,MAAM,KACJ,kOACF;EACA,OAAO,MAAM,KAAK,IAAI;CACxB;AACF"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Names the cards a board lists and when each last changed, whatever their order. The server sends
3
+ * it with the cards that moved; a reader that kept the board computes it over its merged copy, and
4
+ * a different value means that copy missed a change. 32-bit integer sums, so no size of board
5
+ * rounds it.
6
+ */
7
+ export declare function boardCheck(cards: readonly {
8
+ id: string;
9
+ changedAt?: Date | string | null;
10
+ }[]): string;
11
+ //# sourceMappingURL=board-check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board-check.d.ts","sourceRoot":"","sources":["../../src/work-items/board-check.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,CAAA;CAAE,EAAE,GAAG,MAAM,CAUrG"}